#include <WiFi.h>
#include <ThingsBoard.h>
#include <Arduino_MQTT_Client.h>
#include <ArduinoHttpClient.h>
#include <PubSubClient.h>
//define sound speed in cm/uS
#define SOUND_SPEED 0.034
#define CM_TO_INCH 0.393701
#define TB_SERVER "thingsboard.cloud"
#define TB_TOKEN "hckahh54nuw6ngj7daiy"
const int trigPin = 17;
const int echoPin = 18;
#define WIFI_AP "Wokwi-GUEST"
#define WIFI_PASS ""
constexpr uint16_t MAX_MESSAGE_SIZE = 128U;
// Sensor -> ESP32 -> WiFi Client -> Arduino_MQTT_Client -> TB
WiFiClient espClient;
Arduino_MQTT_Client mqttClient(espClient);
ThingsBoard tb(mqttClient, MAX_MESSAGE_SIZE);
long duration;
float distanceCm;
float distanceInch;
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
Serial.begin(115200); // Starts the serial communication
pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
pinMode(echoPin, INPUT); // Sets the echoPin as an Input
// Connect to WiFi
WiFi.begin(WIFI_AP, WIFI_PASS);
Serial.println("Connecting to WiFi...");
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("\nWiFi connected!");
Serial.print("IP Address: ");
Serial.println(WiFi.localIP());
// Connect to ThingsBoard
Serial.println("Connecting to ThingsBoard Server....");
// 2 parameters - 1. TB_Server 2. TB_Token
while(!tb.connect(TB_SERVER, TB_TOKEN)) {
Serial.println("Failed to connect to ThingsBoard...");
delay(500);
}
Serial.println("Connected to ThingsBoard...");
}
void loop() {
// Clears the trigPin
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
// Sets the trigPin on HIGH state for 10 micro seconds
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
// Reads the echoPin, returns the sound wave travel time in microseconds
duration = pulseIn(echoPin, HIGH);
// Calculate the distance
distanceCm = duration * SOUND_SPEED/2;
// Convert to inches
distanceInch = distanceCm * CM_TO_INCH;
// Prints the distance in the Serial Monitor
Serial.print("Distance (cm): ");
Serial.println(distanceCm);
Serial.print("Distance (inch): ");
Serial.println(distanceInch);
// Send date to TB
String jsonData = "{\"Distance\":"+ String(distanceCm) +"}";
tb.sendTelemetryJson(jsonData.c_str());
Serial.println("Data is passed to ThingsBoard");
String jsonData1 = "{\"Distance_INCH\":"+ String(distanceInch) +"}";
tb.sendTelemetryJson(jsonData1.c_str());
Serial.println("Data is passed to ThingsBoard");
delay(1000);
}