วันพุธที่ 25 พฤษภาคม พ.ศ. 2559

NODEMCU-DS18B20 with ThingSpeak

NodeMCU-DS18B20-ThingSpeak

NODEMCU-DS18B20-ThingSpeak


เขียนโค้ดและโหลดลงบอร์ด NODEMCU ได้ดังนี้

#include <esp8266wifi .h>  
#include <onewire .h>  
#include <dallastemperature .h> 
#define ONE_WIRE_BUS D3 
const char* ssid = "MKY_true_FTTx"; // กำหนด SSID[Wifi] (อย่าลืมแก้เป็นของตัวเอง) 
const char* password = "08199928031"; // กำหนด Password [Wifi](อย่าลืมแก้เป็นของตัวเอง)"; 
String apiKey = "XY0S5VLCFF5BMNDK";  // API KEY ที่ได้จาก ThingSpeak
const char* server = "api.thingspeak.com";  
OneWire oneWire(ONE_WIRE_BUS); 
DallasTemperature sensors(&oneWire); 
WiFiClient client; 
void setup()
{ Serial.begin(115200); 
delay(1000);
sensors.begin();
Serial.println(); 
Serial.println(); 
Serial.print("Connecting to "); 
Serial.println(ssid);
WiFi.begin(ssid, password); 
while (WiFi.status() != WL_CONNECTED)
{ delay(500); 
Serial.print("."); 
}
Serial.println("");
Serial.println("WiFi connected"); 
Serial.println("IP address: "); 
Serial.println(WiFi.localIP()); 
} 
void loop() 
{ Serial.println("-------------------------");
Serial.print("Requesting temperatures...");
sensors.requestTemperatures(); // Send the command to get temperatures 
float cTemp = sensors.getTempCByIndex(0); 
Serial.print("Temperature is: "); Serial.println(cTemp, 4); // Display Temperature 
if (client.connect(server, 80)) // "184.106.153.149" or api.thingspeak.com 
{ String postStr = apiKey;  
postStr += "&field1="; 
postStr += String(cTemp); 
postStr += "\r\n\r\n"; 
client.print("POST /update HTTP/1.1\n");  
client.print("Host: api.thingspeak.com\n");
client.print("Connection: close\n"); 
client.print("X-THINGSPEAKAPIKEY: " + apiKey + "\n"); 
client.print("Content-Type: application/x-www-form-urlencoded\n"); 
client.print("Content-Length: "); 
client.print(postStr.length()); 
client.print("\n\n"); 
client.print(postStr); 
Serial.print("Temperature('C)= "); 
Serial.println(cTemp, 4); 
} 
client.stop(); 
Serial.println("Waiting..."); 
delay(20000); // thingspeak needs minimum 15 sec delay between updates 
} 
   
Share:

0 ความคิดเห็น:

แสดงความคิดเห็น