/* Cayenne Ethernet Example This sketch connects to the Cayenne server using an Arduino Ethernet Shield W5100 and runs the main communication loop. The Cayenne Library is required to run this sketch. If you have not already done so you can install it from the Arduino IDE Library Manager. Steps: 1. Set the token variable to match the Arduino token from the Dashboard. 2. Compile and upload this sketch. For Cayenne Dashboard widgets using digital or analog pins this sketch will automatically send data on those pins to the Cayenne server. If the widgets use Virtual Pins, data should be sent to those pins using virtualWrites. Examples for sending and receiving Virtual Pin data are under the Basics folder. */ //#define CAYENNE_DEBUG // Uncomment to show debug messages #define CAYENNE_PRINT Serial // Comment this out to disable prints and save space #include #define echoPin 7 // Echo Pin #define trigPin 8 // Trigger Pin #define LEDPin 2 // LED #define VIRTUAL_PIN V1 // Cayenne authentication token. This should be obtained from the Cayenne Dashboard. char token[] = "token"; 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); pinMode(trigPin, OUTPUT); pinMode(echoPin, INPUT); pinMode(LEDPin, OUTPUT); // Use LED indicator (if required) } 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"); digitalWrite(LEDPin, HIGH); } else { /* Send the distance to the computer using Serial protocol, and turn LED OFF to indicate successful reading. */ Serial.println(distance); digitalWrite(LEDPin, LOW); } //Delay 50ms before next reading. delay(50); } CAYENNE_OUT(VIRTUAL_PIN) { Cayenne.virtualWrite(VIRTUAL_PIN, distance); }