ทดลอง ESP32 วัดค่าจาก DHT22 ส่งขึ้นแพลตฟอร์ม

ไอโอทีเส้นทางสู่เมืองอัจฉริยะ

Created with Sketch.

ทดลอง ESP32 วัดค่าจาก DHT22 ส่งขึ้นแพลตฟอร์ม

วันนี้นำเอาโค้ดสำหรับ ESP32  มาให้ดาวน์โหลดไปทดสอบกัน

เป็นตัวอย่างสำหรับการ ใช้งาน  กับ  Sensor  DHT22 และส่งข้อมูลไปเก็บยังแพลตฟอร์ม  IOT  ของเรา

การติดตั้ง  Sensor เข้ากับ  ESP32   ใช้สัญญาณต่อเข้ากับ  GPIO 17  และบวก  ที่  3V3 ลบ  ที่ GND ตามปกติ

ส่วนของโค้ด  ก็ตามด้านล่างนี่เลย

Library ที่ใช้ในกรณีนี้คือ  DHTesp.h  และ  WiFi.h

Host  ที่อ้างอิงถึง  คือ  otrixiot.com

ตัวแปรสำหรับการส่งค่า  อุณหภูมิคือ  data1  = temp_0  ที่ได้มาจาก  function ของ DHT  และ  data2 = humid_0

การทดสอบผ่านไปได้อย่างฉลุยครับ

  1. /*
  2. * This sketch sends data via HTTP GET requests to data.sparkfun.com service.
  3. *
  4. * You need to get streamId and privateKey at data.sparkfun.com and paste them
  5. * below. Or just customize this script to talk to other HTTP servers.
  6. * Set board NodeMCU-32S pr ESP32 Dev Module
  7. * Set Programmer AVRISP mkll
  8. */
  9. //===== DHT setting
  10. #include “DHTesp.h”
  11. #include “Ticker.h”
  12. #ifndef ESP32
  13. #pragma message(THIS EXAMPLE IS FOR ESP32 ONLY!)
  14. #error Select ESP32 board.
  15. #endif
  16. //=========
  17. #include <WiFi.h>
  18. //======
  19. DHTesp dht;
  20. void tempTask(void *pvParameters);
  21. bool getTemperature();
  22. void triggerGetTemp();
  23. /** Task handle for the light value read task */
  24. TaskHandle_t tempTaskHandle = NULL;
  25. /** Ticker for temperature reading */
  26. Ticker tempTicker;
  27. /** Comfort profile */
  28. ComfortState cf;
  29. /** Flag if task should run */
  30. bool tasksEnabled = false;
  31. /** Pin number for DHT11 data pin */
  32. int dhtPin = 17;
  33. /**
  34. * initTemp
  35. * Setup DHT library
  36. * Setup task and timer for repeated measurement
  37. * @return bool
  38. * true if task and timer are started
  39. * false if task or timer couldn’t be started
  40. */
  41. //====
  42. const char* ssid = “Arsenae_2.4G”;
  43. const char* password = “kb075699212”;
  44. //const char* ssid = “dlink_DWR-932C_0C4E”;
  45. //const char* password = “gkyVD35784”;
  46. const char* host = “otrixiot.com”;
  47. const char* code = “ESP32-002”;
  48. float temp_0 = 0;
  49. float humid_0 = 0;
  50. float vHumidity = 0;
  51. float vTemperature = 0;
  52. float data1=55;
  53. float data2=33;
  54. float data3=33;
  55. float data4=33;
  56. float data5=33;
  57. float data6=33;
  58. float data7=33;
  59. float data8=33;
  60. float data9=33;
  61. float data10=33;
  62. float data11=33;
  63. float data12=33;
  64. float data13=33;
  65. float data14=33;
  66. float data15=33;
  67. float data16=33;
  68. float data17=33;
  69. float data18=33;
  70. float data19=33;
  71. float data20=33;
  72. /*
  73. void setup_Sensor_Box_Temperature()
  74. {
  75. dht.begin();
  76. }
  77. */
  78. /// ===
  79. bool initTemp() {
  80. byte resultValue = 0;
  81. // Initialize temperature sensor
  82. dht.setup(dhtPin, DHTesp::DHT22);
  83. Serial.println(“DHT initiated”);
  84. // Start task to get temperature
  85. xTaskCreatePinnedToCore(
  86. tempTask, /* Function to implement the task */
  87. “tempTask “, /* Name of the task */
  88. 4000, /* Stack size in words */
  89. NULL, /* Task input parameter */
  90. 5, /* Priority of the task */
  91. &tempTaskHandle, /* Task handle. */
  92. 1); /* Core where the task should run */
  93. if (tempTaskHandle == NULL) {
  94. Serial.println(“Failed to start task for temperature update”);
  95. return false;
  96. } else {
  97. // Start update of environment data every 20 seconds
  98. tempTicker.attach(20, triggerGetTemp);
  99. }
  100. return true;
  101. }
  102. /**
  103. * triggerGetTemp
  104. * Sets flag dhtUpdated to true for handling in loop()
  105. * called by Ticker getTempTimer
  106. */
  107. void triggerGetTemp() {
  108. if (tempTaskHandle != NULL) {
  109. xTaskResumeFromISR(tempTaskHandle);
  110. }
  111. }
  112. /**
  113. * Task to reads temperature from DHT11 sensor
  114. * @param pvParameters
  115. * pointer to task parameters
  116. */
  117. void tempTask(void *pvParameters) {
  118. Serial.println(“tempTask loop started”);
  119. while (1) // tempTask loop
  120. {
  121. if (tasksEnabled) {
  122. // Get temperature values
  123. getTemperature();
  124. }
  125. // Got sleep again
  126. vTaskSuspend(NULL);
  127. }
  128. }
  129. /**
  130. * getTemperature
  131. * Reads temperature from DHT11 sensor
  132. * @return bool
  133. * true if temperature could be aquired
  134. * false if aquisition failed
  135. */
  136. bool getTemperature() {
  137. // Reading temperature for humidity takes about 250 milliseconds!
  138. // Sensor readings may also be up to 2 seconds ‘old’ (it’s a very slow sensor)
  139. TempAndHumidity newValues = dht.getTempAndHumidity();
  140. // Check if any reads failed and exit early (to try again).
  141. if (dht.getStatus() != 0) {
  142. Serial.println(“DHT error status: ” + String(dht.getStatusString()));
  143. return false;
  144. }
  145. float heatIndex = dht.computeHeatIndex(newValues.temperature, newValues.humidity);
  146. float dewPoint = dht.computeDewPoint(newValues.temperature, newValues.humidity);
  147. float cr = dht.getComfortRatio(cf, newValues.temperature, newValues.humidity);
  148. String comfortStatus;
  149. switch(cf) {
  150. case Comfort_OK:
  151. comfortStatus = “Comfort_OK”;
  152. break;
  153. case Comfort_TooHot:
  154. comfortStatus = “Comfort_TooHot”;
  155. break;
  156. case Comfort_TooCold:
  157. comfortStatus = “Comfort_TooCold”;
  158. break;
  159. case Comfort_TooDry:
  160. comfortStatus = “Comfort_TooDry”;
  161. break;
  162. case Comfort_TooHumid:
  163. comfortStatus = “Comfort_TooHumid”;
  164. break;
  165. case Comfort_HotAndHumid:
  166. comfortStatus = “Comfort_HotAndHumid”;
  167. break;
  168. case Comfort_HotAndDry:
  169. comfortStatus = “Comfort_HotAndDry”;
  170. break;
  171. case Comfort_ColdAndHumid:
  172. comfortStatus = “Comfort_ColdAndHumid”;
  173. break;
  174. case Comfort_ColdAndDry:
  175. comfortStatus = “Comfort_ColdAndDry”;
  176. break;
  177. default:
  178. comfortStatus = “Unknown:”;
  179. break;
  180. };
  181. temp_0 = newValues.temperature;
  182. humid_0 = newValues.humidity;
  183. // Serial.println(” T:” + String(newValues.temperature) + ” H:” + String(newValues.humidity) + ” I:” + String(heatIndex) + ” D:” + String(dewPoint) + ” ” + comfortStatus);
  184. return true;
  185. }
  186. void DHT22setup()
  187. {
  188. Serial.begin(115200);
  189. Serial.println();
  190. Serial.println(“DHT ESP32 example with tasks”);
  191. initTemp();
  192. // Signal end of setup() to tasks
  193. tasksEnabled = true;
  194. }
  195. // Main setup ========
  196. void setup()
  197. {
  198. Serial.begin(115200);
  199. DHT22setup();
  200. delay(10);
  201. // We start by connecting to a WiFi network
  202. Serial.println();
  203. Serial.println();
  204. Serial.print(“Connecting to “);
  205. Serial.println(ssid);
  206. WiFi.begin(ssid, password);
  207. while (WiFi.status() != WL_CONNECTED) {
  208. delay(500);
  209. Serial.print(“.”);
  210. }
  211. Serial.println(“”);
  212. Serial.println(“WiFi connected”);
  213. Serial.println(“IP address: “);
  214. Serial.println(WiFi.localIP());
  215. }
  216. int value = 0;
  217. void loop()
  218. {
  219. delay(5000);
  220. DHT22_loop();
  221. // scanSensor_Box_Temperature();
  222. //data1 = vTemperature;
  223. ++value;
  224. data1 = temp_0;
  225. data2 = humid_0;
  226. Serial.print(“connecting to “);
  227. Serial.println(host);
  228. // Use WiFiClient class to create TCP connections
  229. WiFiClient client;
  230. const int httpPort = 80;
  231. if (!client.connect(host, httpPort)) {
  232. Serial.println(“connection failed”);
  233. return;
  234. }
  235. // We now create a URI for the request
  236. String url = “/api/insertData?device_id=” + String(65)+”&code=”+String(code)+”&data1=” +String(data1) +”&data2=”
  237. + String(data2)+”&data3=” +String(data3)+”&data4=” +String(data4)+”&data5=” +String(data5)
  238. +”&data6=” +String(data6)+”&data7=” +String(data7)+”&data8=” +String(data8)+”&data9=” +String(data9)
  239. +”&data10=” +String(data10)+”&data11=” +String(data11)+”&data12=” +String(data12)+”&data13=” +String(data13)
  240. +”&data14=” +String(data14)+”&data15=” +String(data15)+”&data16=” +String(data16)+”&data17=” +String(data17)
  241. +”&data18=” +String(data18)+”&data19=” +String(data19)+”&data20=” +String(data20);
  242. Serial.print(“Requesting URL: “);
  243. Serial.println(url);
  244. // This will send the request to the server
  245. client.print(String(“GET “) + url + ” HTTP/1.1\r\n” +
  246. “Host: ” + host + “\r\n” +
  247. “Connection: close\r\n\r\n”);
  248. unsigned long timeout = millis();
  249. while (client.available() == 0) {
  250. if (millis() – timeout > 5000) {
  251. Serial.println(“>>> Client Timeout !”);
  252. client.stop();
  253. return;
  254. }
  255. }
  256. // Read all the lines of the reply from server and print them to Serial
  257. while(client.available()) {
  258. String line = client.readStringUntil(‘\r’);
  259. //Serial.print(line);
  260. }
  261. Serial.println();
  262. Serial.println(“closing connection”);
  263. delay(50000);
  264. }
  265. void DHT22_loop() {
  266. if (!tasksEnabled) {
  267. // Wait 2 seconds to let system settle down
  268. delay(2000);
  269. // Enable task that will read values from the DHT sensor
  270. tasksEnabled = true;
  271. if (tempTaskHandle != NULL) {
  272. vTaskResume(tempTaskHandle);
  273. }
  274. }
  275. //yield();
  276. }

แถมแหล่งอ้างอิงสำหรับการศึกษา  ESP32 ตามนี้เลยครับ  https://microcontrollerslab.com/esp32-pinout-use-gpio-pins/