#define CAYENNE_PRINT Serial
#include <CayenneMQTTESP32.h>
#include <WiFi.h>

char ssid[] = "LPU Wireless";
char wifiPassword[] = "123456789a";
char username[] = "yfd4b4870-b284-11ed-b72d-d9f6595c5b9d";
char password[] = "346c9c8bab56d3635495551b271eb6e305cc8533";
char clientID[] = "5c128330-be58-11ed-b0e7-e768b61d6137";

void setup() {
  Serial.begin(9600);
  delay(1000);

  // Connect to Wi-Fi network
  WiFi.begin(ssid, wifiPassword);
  Serial.print("Connecting to Wi-Fi");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("Wi-Fi connected successfully");

  // Connect to Cayenne MQTT server
  Cayenne.begin(username, password, clientID);
}

void loop() {
  Cayenne.loop();
  publishdata();
  delay(500); // reduce the delay time to update the distance value more frequently
}

void publishdata() {
  digitalWrite(12, LOW);
  delayMicroseconds(2);
  digitalWrite(12, HIGH);
  delayMicroseconds(10);
  digitalWrite(12, LOW);
  long duration = pulseIn(14, HIGH); // use a long variable to store the duration
  float distance = duration * 0.034 / 2;
  if (distance > 0 && distance < 400) { // add error checking to ensure the distance is within a reasonable range
    Cayenne.virtualWrite(0, distance); // use the correct channel number (0 instead of V0)
    Serial.print("Distance: ");
    Serial.print(distance);
    Serial.println(" cm");
  }
}