//#define CAYENNE_DEBUG // Uncomment to show debug messages #define CAYENNE_PRINT Serial // Comment this out to disable prints and save space #include "CayenneDefines.h" #include "BlynkSimpleEsp8266.h" #include "CayenneWiFiClient.h" #define echoPin 5 // Echo Pin #define trigPin 4 // Trigger Pin #define VIRTUAL_PIN V1 // Cayenne authentication token. This should be obtained from the Cayenne Dashboard. char token[] = "token"; // Your network name and password. char ssid[] = "ssid"; char password[] = "password"; int maximumRange = 200; // Maximum range needed int minimumRange = 0; // Minimum range needed long duration, distance; // Duration used to calculate distance void setup() { Serial.begin(9600); Cayenne.begin(token, ssid, password); pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); } void loop() { Cayenne.run(); digitalWrite(trigPin, LOW); delayMicroseconds(2); digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); duration = pulseIn(echoPin, HIGH); //Calculate the distance (in cm) based on the speed of sound. distance = duration/58.2; if (distance >= maximumRange || distance <= minimumRange){ /* Send a negative number to computer and Turn LED ON to indicate "out of range" */ Serial.println("-1"); } else { /* Send the distance to the computer using Serial protocol, and turn LED OFF to indicate successful reading. */ Serial.println(distance); } //Delay 50ms before next reading. delay(50); } CAYENNE_OUT(VIRTUAL_PIN) { Cayenne.virtualWrite(VIRTUAL_PIN, distance); }