#include <WiFi.h>
#include <PubSubClient.h>
// Replace with your network credentials
const char* ssid = "YOUR_SSID";
const char* password = "YOUR_PASSWORD";
// Replace with your ThingsBoard instance and token
const char* mqtt_server = "YOUR_THINGSBOARD_SERVER";
const char* token = "ccD7Hcq1crrAPrLrbhRN";
// Initialize the WiFi and MQTT client objects
WiFiClient espClient;
PubSubClient client(espClient);
// Analog pin connected to the potentiometer
const int potPin = 34;
void setup() {
// Initialize Serial Monitor
Serial.begin(115200);
delay(10);
// Connecting to WiFi
setup_wifi();
// Set the MQTT server
client.setServer(mqtt_server, 1883);
}
void setup_wifi() {
delay(10);
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
void reconnect() {
// Loop until we're reconnected
while (!client.connected()) {
Serial.print("Attempting MQTT connection...");
// Attempt to connect
if (client.connect("ESP32Client", token, "")) {
Serial.println("connected");
} else {
Serial.print("failed, rc=");
Serial.print(client.state());
Serial.println(" try again in 3 seconds");
// Wait 3 seconds before retrying
delay(3000);
}
}
}
void loop() {
if (!client.connected()) {
reconnect();
}
client.loop();
// Read the value from the potentiometer
int potValue = analogRead(potPin);
// Print the potentiometer value to the Serial Monitor
Serial.print("Potentiometer value: ");
Serial.println(potValue);
// Prepare payload in JSON format
String payload = "{\"adc_value\":";
payload += potValue;
payload += "}";
// Publish the payload to ThingsBoard
if (client.publish("v1/devices/me/telemetry", payload.c_str())) {
Serial.println("Data sent successfully");
} else {
Serial.println("Failed to send data");
}
// Delay for a second before next reading
delay(100);
}