//----------------------------------------Include the NodeMCU ESP8266 Library
//----------------------------------------see here: https://www.youtube.com/watch?v=8jMr94B8iN0 to add NodeMCU ESP8266 library and board
#include <WiFi.h>
//----------------------------------------Include the ThingSpeak Library, Download here : https://github.com/mathworks/thingspeak-arduino
#include "ThingSpeak.h"
#include <ESP32Servo.h>
#define ON_Board_LED 5 //--> Defining an On Board LED, used for indicators when the process of connecting to a wifi router
#define LIGHT 1 //--> Defining LIGHT/Relay Port
const int servoPin = 0;
Servo servo;
//----------------------------------------SSID and Password of your WiFi router/hotspot
const char *ssid = "Wokwi-GUEST";
const char *password = "";
//----------------------------------------Channel ID on ThingSpeak
unsigned long channel = 2377889;
//----------------------------------------Declaration field1, I use field1 for light / relay, if you use many fields, add field1, field2, and so on.
unsigned int field1 = 3;
WiFiClient client;
//----------------------------------------SETUP
void setup() {
Serial.begin(115200);
delay(100);
pinMode(LIGHT, OUTPUT); //--> LIGHT/Relay port Direction output
digitalWrite(LIGHT, LOW); //--> Turn off LIGHT. LIGHT/Relay use active high, some relay modules may be different.
//----------------------------------------Wait for connection
WiFi.begin(ssid, password);
Serial.println("");
Serial.print("Connecting");
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
}
Serial.println("");
Serial.print("Successfully connected to : ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
Serial.print("Netmask: ");
Serial.println(WiFi.subnetMask());
Serial.print("Gateway: ");
Serial.println(WiFi.gatewayIP());
//----------------------------------------ThingSpeak.begin(client)
servo.attach(servoPin, 500, 2400);
ThingSpeak.begin(client);
}
int pos = 0;
void loop() {
int statusCode = 0;
int last_light_state = ThingSpeak.readFloatField(channel, field1); //--> get the latest data from the fields on ThingSpeak
statusCode = ThingSpeak.getLastReadStatus(); //--> Check the status of the read operation to see if it was successful
if(statusCode == 200){
if(last_light_state == 1){
digitalWrite(LIGHT, HIGH);
Serial.println("LIGHT is On");
for (; pos <= 180; pos += 1) {
servo.write(pos);
delay(15);
}
}
else if(last_light_state == 0){
digitalWrite(LIGHT, LOW);
Serial.println("LIGHT is Off");
for (; pos >= 0; pos -= 1) {
servo.write(pos);
delay(15);
}
}
Serial.print("The latest data from Field1 on ThingSpeak is : ");
Serial.println(last_light_state);
}
else {
Serial.println("Problem reading channel. HTTP error code " + String(statusCode));
}
delay(150);
}