#include <WiFi.h>
#include <PubSubClient.h>
#define WIFI_SSID "Wokwi-GUEST"
#define WIFI_PASSWORD ""
#define THINGSBOARD_SERVER "134.209.149.220"
#define THINGSBOARD_PORT 1883
#define THINGSBOARD_TOKEN "5p7e6iurfxo3o4fnk6pn"
WiFiClient wifiClient;
PubSubClient client(wifiClient);
#define VOLTAGE_PIN 32
#define buttonPin1 23
#define buttonPin2 5
#define buttonPin3 18
#define buttonPin4 19
#define buttonPin5 21
#define buttonPin6 3
#define buttonPin7 1
#define buttonPin8 22
bool send_data = false;
bool connected = false;
uint8_t TP[8] = {0};
uint8_t send_TP[9] = {8};
void setup() {
pinMode(VOLTAGE_PIN, INPUT);
pinMode(buttonPin1, INPUT);
pinMode(buttonPin2, INPUT);
pinMode(buttonPin3, INPUT);
pinMode(buttonPin4, INPUT);
pinMode(buttonPin5, INPUT);
pinMode(buttonPin6, INPUT);
pinMode(buttonPin7, INPUT);
pinMode(buttonPin8, INPUT);
Serial.begin(115200);
Serial.println("Start...");
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
Serial.println("Connecting to WiFi...");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("WiFi connected");
client.setServer(THINGSBOARD_SERVER, THINGSBOARD_PORT);
Serial.println("Connecting to MQTT...");
while (!client.connected()) {
if (client.connect("ESP32_Client", THINGSBOARD_TOKEN, NULL)) {
Serial.println("MQTT connected");
connected = true;
}
}
}
void loop() {
delay(100);
uint8_t c_TP[8] = {0};
c_TP[0] = digitalRead(buttonPin1) == HIGH ? 1 : 0;
c_TP[1] = digitalRead(buttonPin2) == HIGH ? 1 : 0;
c_TP[2] = digitalRead(buttonPin3) == HIGH ? 1 : 0;
c_TP[3] = digitalRead(buttonPin4) == HIGH ? 1 : 0;
c_TP[4] = digitalRead(buttonPin5) == HIGH ? 1 : 0;
c_TP[5] = digitalRead(buttonPin6) == HIGH ? 1 : 0;
c_TP[6] = digitalRead(buttonPin7) == HIGH ? 1 : 0;
c_TP[7] = digitalRead(buttonPin8) == HIGH ? 1 : 0;
bool anyChange = false;
for (uint8_t x = 0; x < 8; x++) {
if (c_TP[x] != TP[x]) {
anyChange = true;
break;
}
}
if (anyChange) {
send_data = true;
}
int16_t ADC = analogRead(VOLTAGE_PIN);
float voltage = ((float)ADC / 4095.0) * 300.0;
String voltage_S = String(voltage, 1);
Serial.print("Voltage: ");
Serial.println(voltage_S);
if (voltage < 200.0 || voltage > 230.0) {
send_data = true;
send_TP[8] = 1;
}
if (send_data) {
send_data = false;
if (!client.connected()) {
while (!client.connected()) {
if (client.connect("ESP32_Client", THINGSBOARD_TOKEN, NULL)) {
Serial.println("MQTT reconnected");
}
}
}
for (uint8_t x = 0; x < 8; x++) {
if (send_TP[x] == 1 || c_TP[x] != TP[x]) {
// Updated data key to send as 1, 2, 3, 4, etc.
String data = "{\"" + String(x + 1) + "\":" + (c_TP[x] ? "true" : "false") + "}";
client.publish("v1/devices/me/telemetry", data.c_str());
send_TP[x] = 0;
}
}
if (send_TP[8] == 1) {
String dataV = "{\"V\":" + voltage_S + "}";
client.publish("v1/devices/me/telemetry", dataV.c_str());
send_TP[8] = 0;
}
for (uint8_t x = 0; x < 8; x++) {
TP[x] = c_TP[x];
}
}
}