#include <WiFi.h>
#include <ThingsBoard.h>
#include <Arduino_MQTT_Client.h>
#define BAUD_RATE 115200
#define NTC_TEMP_PIN A0
#define ADC_MAX 4095.0
#define CELSIUS_TO_KELVIN 273.15
// ThingsBoard
#define TB_SERVER "thingsboard.cloud"
#define TOKEN "hyBwTmT6AyCS1GmhFXvF"
constexpr uint16_t MAX_MESSAGE_SIZE = 256U;
// WiFi
const char *ssid = "Wokwi-GUEST";
const char *password = "";
WiFiClient espClient;
Arduino_MQTT_Client mqttClient(espClient);
ThingsBoard tb(mqttClient, MAX_MESSAGE_SIZE);
const float BETA = 3950;
const float MIN_VALUE = 298.15;
int getTemp(int analogValue) {
float celsius = 1 / (log(1 / (ADC_MAX / analogValue - 1)) / BETA + 1.0 / MIN_VALUE) - CELSIUS_TO_KELVIN;
return celsius;
}
void setup() {
Serial.begin(BAUD_RATE);
pinMode(NTC_TEMP_PIN, INPUT);
// Connecting to a Wi-Fi network
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.println("Connecting to WiFi..");
}
Serial.println("Connected to the Wi-Fi network");
// Connecting to ThingsBoard
connectToThingsBoard();
}
void connectToThingsBoard() {
if (!tb.connected()) {
Serial.println("Connecting to ThingsBoard server");
if (!tb.connect(TB_SERVER, TOKEN)) {
Serial.println("Failed to connect to ThingsBoard");
} else {
Serial.println("Connected to ThingsBoard");
}
}
}
void sendDataToThingsBoard(float temp) {
String jsonData = "{\"tempIn\":" + String(temp) + "}";
tb.sendTelemetryJson(jsonData.c_str());
Serial.println("Data sent to ThingsBoard");
}
void loop() {
// Convert voltage to temp
int NTC_Raw = analogRead(NTC_TEMP_PIN);
int NTC_Temp = getTemp(NTC_Raw);
Serial.print("Temperature: ");
Serial.print(NTC_Temp);
Serial.println();
if (!tb.connected()) {
connectToThingsBoard();
}
sendDataToThingsBoard(NTC_Temp);
tb.loop();
delay(1500);
}