#include <WiFi.h>
#include <WiFiClient.h>
#include <ESPAsyncWebSrv.h>
#include <ThingSpeak.h>
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// ThingSpeak settings
const char* thingSpeakServer = "api.thingspeak.com";
const char* apiKey = "BYMOTVVZBG25BVUU";
const unsigned long channelID = 2303812;
AsyncWebServer server(80);
bool isBikeUnlocked = false; // Initially, the bike is locked
const int ledPin = 13; // GPIO pin to which your LED is connected
unsigned long unlockTime = 0;
unsigned long lockTime = 0;
void setup() {
// Initialize Serial Monitor
Serial.begin(115200);
// Connect to Wi-Fi
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Connecting to WiFi...");
}
Serial.println("Connected to WiFi");
WiFiClient client;
// Initialize ThingSpeak
ThingSpeak.begin(client);
// Configure the LED pin as an OUTPUT
pinMode(ledPin, OUTPUT);
// Handle URL request to lock/unlock the bike
server.on("/bike", HTTP_GET, [](AsyncWebServerRequest *request){
String action = request->arg("action");
if (action == "lock") {
if (isBikeUnlocked) {
digitalWrite(ledPin, LOW); // Turn off the LED
isBikeUnlocked = false;
lockTime = millis();
sendToThingSpeak(lockTime - unlockTime, false); // Calculate and send time to ThingSpeak
request->send(200, "text/plain", "Bike Locked");
}
} else if (action == "unlock") {
if (!isBikeUnlocked) {
digitalWrite(ledPin, HIGH); // Turn on the LED
isBikeUnlocked = true;
unlockTime = millis();
sendToThingSpeak(0, true); // Send an unlock event to ThingSpeak
request->send(200, "text/plain", "Bike Unlocked");
}
}
});
// Start server
server.begin();
}
void sendToThingSpeak(unsigned long time, bool unlockEvent) {
if (ThingSpeak.writeField(channelID, unlockEvent ? 1 : 2, unlockEvent ? 1 : 0, apiKey)) {
Serial.println("Data sent to ThingSpeak.");
} else {
Serial.println("Failed to send data to ThingSpeak.");
}
}
void loop() {
// You can add additional functionality or checks here if needed
}