//Blink an LED with delay of 2 seconds using ESP32 Microcontroller
#include <WiFi.h>
#include <PubSubClient.h>
#define LED1 26 // external LED
//Wokwi WiFi
const char* ssid = "Wokwi-GUEST";
const char* pass = "";
const char* host = "api.thingspeak.com";
// Your Write API Key
const char* writeAPIKey = "7T6UFRNUH1CHP4XV";
void setup() {
Serial.begin(115200);
pinMode(LED1, OUTPUT);
Serial.println("Connecting to WiFi...");
WiFi.begin(ssid, pass, 6); // Channel 6 for Wokwi
while (WiFi.status() != WL_CONNECTED) {
delay(100);
Serial.println("Connecting...");
}
Serial.println("WiFi Connected!");
Serial.println(WiFi.localIP());
}
void loop() {
// ===== LED ON =====
digitalWrite(LED1, HIGH);
Serial.println("LED ON");
sendToThingSpeak(1); // Send LED status = 1
delay(1000); // ThingSpeak update limit
// ===== LED OFF =====
digitalWrite(LED1, LOW);
Serial.println("LED OFF");
sendToThingSpeak(0); // Send LED status = 0
delay(1000); // ThingSpeak update limit
}
void sendToThingSpeak(int ledStatus) {
WiFiClient client;
if (!client.connect(host, 80)) {
Serial.println("ThingSpeak Connection Failed!");
return;
}
String url = "/update?api_key=";
url += writeAPIKey;
url += "&field1="; // send to Field 1
url += String(ledStatus);
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
"Host: " + host + "\r\n" +
"Connection: close\r\n\r\n");
Serial.println("Data Sent to ThingSpeak: " + String(ledStatus));
}Loading
esp32-devkit-c-v4
esp32-devkit-c-v4