#include <WiFi.h>
#include <WiFiClient.h>
#include <ThingSpeak.h>
#include <DallasTemperature.h>
#include <OneWire.h>
int sensorPin = 14;
OneWire oneWire (sensorPin); // creates the OneWire object using a specific pin
DallasTemperature sensor (&oneWire);
//Name of router and password
const char* ssid="Wokwi-GUEST";
const char* password="";
const int trigPin = 16;
const int echoPin = 17;
#define SOUND_SPEED 0.034
#define CM_TO_INCH 0.393701
long duration;
int distanceCm;
int distanceInch;
//thingSpeak setting
unsigned long channelNumber = 2597562;
const char* WriteAPIKey = "150ITO87ME17BFXZ";
WiFiClient client;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
sensor.begin ();
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT);
WiFi.begin(ssid,password);
Serial.println("connecting to wifi.......");
//conect divice wifi
while (WiFi.status() != WL_CONNECTED){
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("connected");
Serial.print("WiFi Address: ");
Serial.println(WiFi.localIP());
ThingSpeak.begin(client);
}
void loop() {
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculate the distance
distanceCm = duration * SOUND_SPEED/2;
// Convert to inches
distanceInch = distanceCm * CM_TO_INCH;
// Prints the distance in the Serial Monitor
Serial.print("Distance (cm): ");
Serial.println(distanceCm);
ThingSpeak.setField(1, distanceCm);
int x = ThingSpeak.writeFields(channelNumber, WriteAPIKey);
if (x == 200){
Serial.println("Success");
}else{
Serial.println("Failed:"+ String(x));
}
delay(1000);
sensor.requestTemperatures ();
float temp = sensor.getTempCByIndex (0);
Serial.print ("Temperature: ");
Serial.print (temp);
Serial.println ("ºC");
delay (3000);
ThingSpeak.setField(2, temp);
int y = ThingSpeak.writeFields(channelNumber, WriteAPIKey);
if (y == 200){
Serial.println("Success");
}else{
Serial.println("Failed:"+ String(y));
}
delay(1000);
}