Cayenne / HCSR04 / NODEMCU

// This example shows how to connect to Cayenne using an Ethernet W5100 shield and send/receive sample data.

//#define CAYENNE_DEBUG
#define CAYENNE_DEBUG
#define CAYENNE_PRINT Serial
#include <CayenneMQTTESP8266.h>

// WiFi network info.
char ssid[] = "XXX";
char wifiPassword[] = "XXX";

// Cayenne authentication info. This should be obtained from the Cayenne Dashboard.
char username[] = "XXX";
char password[] = "XXX";
char clientID[] = "XXX";

unsigned long lastMillis = 0;

// defines pins numbers

const int trigPin = 2;  //D4
const int echoPin = 0;  //D3

// defines variables
long duration;
int distance;
int y;

void setup() {
  Cayenne.begin(username, password, clientID, ssid, wifiPassword);

  pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output
  pinMode(echoPin, INPUT); // Sets the echoPin as an Input
  Serial.begin(9600); // Starts the serial communication
}

void loop() {
  Cayenne.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);

  // Calculating the distance
  distance = duration * 0.034 / 2;
  // Prints the distance on the Serial Monitor
  Serial.print("Distance: ");
  Serial.println(distance);
  y = map(distance, 95, 10, 0, 100);
  y = constrain(y, 0, 100);  
  delay(500);
  if (millis() - lastMillis > 10000) {
    lastMillis = millis();
    Cayenne.virtualWrite(10, distance);
    Cayenne.virtualWrite(13, y, "t1", "null");
  }
}