(no subject)

Oct 08, 2014 10:56

Подключил датчик температуры к сайту http://narodmon.ru/
Всё просто. Ардуина Уно и плата сетевого шилда на en28j60. Датчик Dallas DS18B20.
Проблемой было найти нормальные библиотеки для них.
Ниже код, он работает - взял готовый с какого-то форума.
Перед этим перелопатил много всякого.



  1. //все работает

  2. #include

  3. #include

  4. #include

  5.  

  6. #define ONE_WIRE_BUS 2

  7. String mac ="002B3420DEAD";

  8. float tempC = 0.0;

  9.  

  10. // ethernet interface mac address, must be unique on the LAN

  11. byte mymac[] = {

  12. 0x00,0x2b,0x34,0x20,0xde,0xad };

  13.  

  14. //char website[] PROGMEM = "narodmon.ru:8080";

  15. static byte hisip[] = {

  16. 92,39,235,156,8283 };

  17.  

  18. #define REQUEST_RATE 300000 // milliseconds

  19.  

  20. byte Ethernet::buffer[700];

  21. uint32_t timer;

  22. Stash stash;

  23.  

  24. static char statusstr[10];

  25.  

  26. OneWire oneWire(ONE_WIRE_BUS);

  27. // Pass our oneWire reference to Dallas Temperature.

  28. DallasTemperature sensors(&oneWire);

  29.  

  30. void setup () {

  31. sensors.begin();

  32. Serial.begin(57600);

  33. Serial.println("\n[webClient]");

  34. delay(1000);

  35. if (ether.begin(sizeof Ethernet::buffer, mymac, SS) == 0)

  36. Serial.println( "Failed to access Ethernet controller");

  37. if (!ether.dhcpSetup())

  38. Serial.println("DHCP failed");

  39. //overwrite DNS with google's if there are problems with DNS setup

  40. static byte dnsip[] = {

  41. 8,8,8,8 };

  42. ether.copyIp(ether.dnsip, dnsip);

  43.  

  44. ether.printIp("IP: ", ether.myip);

  45. ether.printIp("GW: ", ether.gwip);

  46. ether.printIp("DNS: ", ether.dnsip);

  47.  

  48. ether.copyIp(ether.hisip, hisip);

  49. ether.printIp("Server: ", ether.hisip);

  50.  

  51. while (ether.clientWaitingGw())

  52. ether.packetLoop(ether.packetReceive());

  53. Serial.println("Gateway found");

  54. timer = - REQUEST_RATE; // start timing out right away

  55.  

  56. }

  57.  

  58. void loop () {

  59. //word len = ether.packetReceive();

  60. //word pos = ether.packetLoop(len);

  61. ether.packetLoop(ether.packetReceive());

  62.  

  63. if (millis() > timer + REQUEST_RATE)

  64. {

  65. timer = millis();

  66. sensors.begin();

  67. sensors.requestTemperatures(); // Send the command to get temperatures

  68. tempC = sensors.getTempCByIndex(0);

  69.  

  70. // we can determine the size of the generated message ahead of time

  71. byte sd = stash.create();

  72.  

  73. stash.print("ID=");

  74. stash.print(mac);

  75. stash.print("&");

  76. stash.print(mac);

  77. stash.print("02");

  78. stash.print("=");

  79. stash.print(tempC);

  80.  

  81. stash.save();

  82.  

  83. Serial.print("ID=");

  84. Serial.print(mac);

  85. Serial.print("&");

  86. Serial.print(mac);

  87. Serial.print("02");

  88. Serial.print("=");

  89. Serial.println(tempC);

  90.  

  91. //tempC+=0.01

  92.  

  93. // generate the header with payload - note that the stash size is used,

  94. // and that a "stash descriptor" is passed in as argument using "$H"

  95. Stash::prepare(PSTR("POST http://narodmon.ru/post.php HTTP/1.0" "\r\n"

  96. "Host: narodmon.ru" "\r\n"

  97. "Content-Length: $D" "\r\n"

  98. "\r\n"

  99. "$H"),

  100. stash.size(), sd);

  101.  

  102. // send the packet - this also releases all stash buffers once done

  103. ether.tcpSend();

  104.  

  105. Serial.println("Done");

  106.  

  107. //Serial.println("Pause start");

  108. //delay(10000);

  109. //Serial.println("Pause end");

  110. }

  111. }

  112.  


https://github.com/milesburton/Arduino-Temperature-Control-Library
https://github.com/davidhbrown/RealTimeClockDS1307
https://github.com/jcw/ethercard

UPD: особенно плохая ситуация с библиотеками для RTC - каждый их лепит сам и их полно лежит недоделанных. Там всё достаточно просто, но использовать готовую всё равно быстрее, поэтому полно воплей на форумах: "ааа, помогите, поставил а оно не работает"; я сам с таким сталкивался, когда не понимая принципов работы ставишь чужой код, а он ведёт себя непредсказуемо. В результате, потеряв кучу времени, находишь причину - она оказывается смехотворной, вроде того, что не на тот пин коннектился, или не ту цифру поменял. Знание принципов всегда лучше, чем скорость. В итоге оно и быстрее выходит.

А для сетевых модулей - может быть проблемой - различия в железе. У моего модуля:

SS 10
MOSI 11
MISO 12
SCK 13
у других может быть по другому. Стандартная ethernet-библиотека ардуины работает с платой на чипе W5100, а не en28j60. Для последней платы - библиотеки появились в инете недавно, созданы энтузиастами. Серверную часть для неё находил уже давно, а теперь нашёл и клиентскую. Теперь можно не только запрашивать у ардуины данные, но и отправлять их сразу с ардуины по расписанию куда-либо в интернет.Или не сервер "умного дома".

arduino

Previous post Next post
Up