In this tutorial, I am going to post data to web server using nodemcu. This is simple example of IoT(Internet of Things). Here I am posting just random data, but it can be data coming from sensor in your case if you choose to do so or use this code snippet for your IoT projects. Below is the code sample with comments where required.
#include <ESP8266HTTPClient.h> //Including Library for making client
#include <ESP8266WiFi.h> //Including Library for connecting to wifi
void setup() {
Serial.begin(115200); //Serial connection for debugging
WiFi.begin("Your_SSID", "Password_For_SSID"); //for WiFi connection
while (WiFi.status() != WL_CONNECTED) {//Wait for the WiFI connection completion
delay(500);
Serial.println("Waiting for connection");
}
Serial.println("Wifi connected");
}
void loop(){
if(WiFi.status() == WL_CONNECTED){ //Check WiFi connection status
HTTPClient http; //Declare object of class HTTPClient
http.begin("http://xxx.xxx.xxx.xxx:xxxx/xxxxx");//Specify request destination
http.addHeader("Content-Type", "text/plain"); //Specify content-type header
http.addHeader("Content-Type", "application/x-www-form-urlencoded");
int httpCode = http.POST("data=3"); //Send data
String payload = http.getString(); //Get the response payload
http.end(); //Close connection
}
delay(3000); //for sending this dummy data at interval of 3 secs
}
No comments:
Post a Comment