#include <Arduino.h>
#include <WiFi.h>
#include <ThingSpeak.h>
#include <ESP32Servo.h>
const char* ssid = "Wokwi-GUEST";
const char* password ="";
void wifiConnect() {
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED)
{
delay (500);
Serial.print (".");
}
Serial.println(" Connected!");
}
const unsigned long channelId = 2326055;
const char* writeAPIKey = "I69NS429DJAZVT4G";
const char* readAPIKey = "SIBX35TA7U9Y3UNC";
WiFiClient client;
class Communication {
public:
virtual void sendData(const String& data) = 0;
virtual int readData() = 0;
virtual void receivedData() = 0;
};
class SerialCommunication : public Communication {
public:
SerialCommunication();
~SerialCommunication();
void sendData(const String& data) override;
int readData();
void receivedData();
};
SerialCommunication::SerialCommunication() {
Serial.begin(9600);
}
SerialCommunication::~SerialCommunication() {
Serial.end();
}
void SerialCommunication::sendData(const String& data) {
Serial.println("sending data to ESP32-C3: " + data);
int ret = ThingSpeak.writeField(channelId, 1, data, writeAPIKey);
if (ret == 200) {
Serial.println("Successful");
} else {
Serial.println("Error");
}
receivedData();
}
int SerialCommunication::readData(){
if (Serial.available()) {
String userInput = Serial.readStringUntil('\n');
sendData(userInput);
return 1;
}
return 0;
}
void SerialCommunication::receivedData(){
String receivedString = ThingSpeak.readStringField(channelId, 1, readAPIKey);
Serial.println("Received String: " + receivedString);
}
void setup ( )
{
Serial.begin(9600);
Serial.print("Connecting to WiFi");
wifiConnect();
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
ThingSpeak.begin(client);
}
void loop() {
SerialCommunication esp32Serial;
if(Serial.available()){
esp32Serial.readData();
}
delay(1000);
}