#include <ESP8266WiFi.h>
String apiKey = "NJBTKNWUNQZWZKO9";
const char *ssid = "vivo Y22";
const char *pass = "20050416";
const char* server = "api.thingspeak.com";
int trigPin1 = D5;
const int echoPin1 = D6;
long duration1;
int distance1;
WiFiClient client;
void setup() {
Serial.begin(9600);
Serial.println("Serial Begin");
pinMode(trigPin1, OUTPUT);
pinMode(echoPin1, INPUT);
WiFi.begin(ssid, pass);
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
}
void loop() {
digitalWrite(trigPin1, LOW);
delayMicroseconds(2);
digitalWrite(trigPin1, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin1, LOW);
duration1 = pulseIn(echoPin1, HIGH) ;
distance1= duration1*0.034/2;
Serial.println("ultra1 =" + String(distance1) + " cm");
int totaldistnace1 =12;
totaldistnace1=totaldistnace1-distance1;
if (client.connect(server, 80))
{
String postStr = apiKey;
postStr += "&field1=";
postStr += String(totaldistnace1);
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("distance1: ");
Serial.print(totaldistnace1);
Serial.print(" ");
}
client.stop();
delay(1000);
}