#include <DHT.h>
#include <WiFi.h>
#include <PubSubClient.h>
const char *ssid="Wokwi-GUEST";
const char *password = "";
// #define TOKEN "rong4hgfdlksz4jig2oy"
#define TOKEN "v8gkiq6m2dyyjbt0gwse"
const char *mqtt_server = "thingsboard.cloud";
WiFiClient wifiClient;
PubSubClient client(wifiClient);
int status = WL_IDLE_STATUS;
#define ADC_VREF_mV 3300.0 // in millivolt
#define ADC_RESOLUTION 4096.0
#define PIN_LM35 34
void setup() {
Serial.begin(115200);
Serial.println("connect to : ");
Serial.println(ssid);
WiFi.begin(ssid,password);
while(WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.println("... ");
}
Serial.println("\n");
Serial.println("IP Address : ");
Serial.println(WiFi.localIP());
Serial.println("\n");
Serial.println("connect to : ");
Serial.println(ssid);
client.setServer(mqtt_server,1883);
}
void loop() {
// Wait a few seconds between measurements.
if(!client.connected()) reconnect();
// read the ADC value from the temperature sensor
int adcVal = analogRead(PIN_LM35);
// convert the ADC value to voltage in millivolt
float milliVolt = adcVal * (ADC_VREF_mV / ADC_RESOLUTION);
// convert the voltage to the temperature in °C
float tempC = milliVolt / 10;
// convert the °C to °F
float tempF = tempC * 9 / 5 + 32;
// print the temperature in the Serial Monitor:
Serial.print("Temperature: ");
Serial.print(tempC); // print the temperature in °C
Serial.print("°C");
Serial.print(" ~ "); // separator between °C and °F
Serial.print(tempF); // print the temperature in °F
Serial.println("°F");
String payload = "{";
payload += ",\"TemperatureC\":";
payload += tempC;
payload += ",\"TemperatureF\":";
payload += tempF;
payload += "}";
Serial.println(payload);
char attributes[1000];
payload.toCharArray(attributes,1000);
client.publish("v1/devices/me/telemetry",attributes);
client.publish("v1/devices/me/attributes",attributes);
Serial.println(attributes);
delay(5000);
}
void reconnect()
{
while(!client.connected())
{
status = WiFi.status();
if(status != WL_CONNECTED)
{
WiFi.begin(ssid,password);
while(WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.println(". ");
}
Serial.println("Connected to AP");
}
Serial.println("Connecting to thingsboard node ..." );
// if(client.connect("7340c300-80a4-11ee-b952-7d878148e30b",TOKEN,""))
if(client.connect("710a26f0-8133-11ee-9581-516a074efd38",TOKEN,""))
{
Serial.println(("Done"));
}
else
{
Serial.println("FAILED, retrying in 5 seconds");
delay(5000);
}
}
}