#include "DHTesp.h"
#include <WiFi.h>
#include <ThingSpeak.h>
char ssid[] = "Wokwi-GUEST";
char pass[] = "";
WiFiClient client;
unsigned long myChannelNumber = 2608261;
const char * myWriteAPIKey = "2SMM7YEBS364PMZG";
int statusCode;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
WiFi.mode(WIFI_STA);
ThingSpeak.begin(client);
const int ledPin = 5;
}
void loop() {
connectToCloud();
writeData();
digitalWrite(ledPin, HIGH); // Turn LED on
delay(1000); // Wait for 1 second
digitalWrite(ledPin, LOW); // Turn LED off
delay(1000); // Wait for 1 second
}
void connectToCloud(){
if(WiFi.status() != WL_CONNECTED) {
Serial.print("Attempting to connect");
while(WiFi.status() != WL_CONNECTED) {
WiFi.begin(ssid, pass);
Serial.print(".");
delay(1000);
}
}
Serial.println("\nConnected.");
}
void writeData(){
ThingSpeak.setField(1, dist);
ThingSpeak.setField(2, data.temperature);
ThingSpeak.setField(3,data.humidity );
statusCode = ThingSpeak.writeFields(myChannelNumber,myWriteAPIKey);
if(statusCode == 200) //successful writing code
Serial.println("Channel update successful.");
else
Serial.println("Problem Writing data. HTTP error code :" +
String(statusCode));
delay(15000); // data to be uploaded every 15secs
}
#include <WiFi.h>
#include <HTTPClient.h>
// Wi-Fi credentials
const char* ssid = "";
const char* password = "";
// ThingSpeak settings
const char* thingSpeakServer = "2632964";
const char* apiKey = "C4F74E9OGJ716GSC"; // Replace with your Write API Key
// Define GPIO pin connected to the LED
const int ledPin = 5; // Change this to the GPIO pin you are using for your LED
void setup() {
// Initialize serial communication
Serial.begin(115200);
// Initialize LED pin as output
pinMode(ledPin, OUTPUT);
// Connect to Wi-Fi
WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("Connected to WiFi");
}
void loop() {
// Example: Toggle LED on and off
digitalWrite(ledPin, HIGH); // Turn LED on
delay(1000); // Wait for 1 second
digitalWrite(ledPin, LOW); // Turn LED off
delay(1000); // Wait for 1 second
// Send data to ThingSpeak
sendDataToThingSpeak(digitalRead(ledPin));
}
void sendDataToThingSpeak(int ledState) {
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
String url = "http://api.thingspeak.com/update?api_key=";
url += apiKey;
url += "&field1=";
url += ledState; // Send 1 if LED is on, 0 if off
http.begin(url);
int httpCode = http.GET();
if (httpCode > 0) {
String payload = http.getString();
Serial.println("ThingSpeak Response: " + payload);
} else {
Serial.println("Error in HTTP request");
}
http.end();
} else {
Serial.println("Error: Not connected to WiFi");
}
}