#include <ESP32Servo.h>
#include <ArduinoJson.h>
#include <WiFi.h>
#include <PubSubClient.h>
#define ServoPIN 18 //Signal Pin
#define GasPIN 34
// Connecting from Wokwi
const char* ssid = "Wokwi-GUEST";
const char* password = "";
// Destination
const char* mqtt_server = "mqtt.thingsboard.cloud";
const char* mqtt_username = "MQ2 Servo";
const char* mqtt_password = "pqrs3241";
const char* clientID = "Gas Detector";
bool ServoState;
Servo myServo; // Servo obj
// RPC Callback
void callback(char* topic, byte* payload, unsigned int length)
{
// Payload to String conversion
char json[length + 1];
memcpy(json, payload, length);
json[length] = '\0';
// Parse JSON
StaticJsonDocument<200> doc;
DeserializationError error = deserializeJson(doc, json);
if (error) {
Serial.println("JSON Parse Error");
return;
}
String method = doc["method"];
bool state = doc["params"];
if (method == "setValue") {
ServoState = state;
// if (state) {
// myServo.write(90);
// Serial.println("Servo ON");
//}
//else {
// myServo.write(0);
//Serial.println("Servo OFF");
//}
}
}
// Client Definition
WiFiClient espClient;
PubSubClient client(espClient);
void setup_wifi() {
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println();
Serial.println("WiFi Connected");
}
void reconnect() {
while (!client.connected()) {
Serial.print("Connecting MQTT...");
if (client.connect(clientID, mqtt_username, mqtt_password)) {
Serial.println("Connected");
client.subscribe("v1/devices/me/rpc/request/+");
}
else {
Serial.print("Failed, rc=");
Serial.println(client.state());
delay(2000);
}
}
}
void setup() {
Serial.begin(115200);
pinMode(ServoPIN, OUTPUT);
//Callback setup
client.setCallback(callback);
// WiFi setup **
setup_wifi();
client.setServer(mqtt_server,1883);
myServo.attach(ServoPIN);
}
void loop() {
if (!client.connected())
reconnect();
client.loop();
int gas = analogRead(GasPIN);
Serial.println(gas);
delay(1000);
if (gas > 2439 && ServoState) {
for (int angle = 0; angle <= 180; angle +=10){
myServo.write(angle); // should give degrees as input
delay(15);
}
for (int angle = 180; angle >= 0; angle -=10){
myServo.write(angle); // should give degrees as input
delay(15);
}
}
else{
myServo.write(0);
}
// Sending data to Dashboard in 5 second intervals!
unsigned long lastSend = 0;
if (millis() - lastSend > 5000) {
lastSend = millis();
char payload[50];
sprintf(payload,"{\"gas\":%d}",gas);
client.publish("v1/devices/me/telemetry",payload);
}
}