About This Project
I have been trying to get a simple code to integrate HC-SR04 ultrasonic sensor to ESP8266 and show the distance on the Cayenne dashboard. There are a few posts on Cayenne similar to this that was done, but couldn’t find one with just HC-SR04 and a NodeMCU so I decided to get it done myself, although I don’t know why I did it, lets just say for the fun of it
I am not a coder, so this might or might not work for others, it worked for me, would look forward to others’ feedback. In the code that I have is what I have put together from a few places and saying that the code might not be perfect. Also, from the Cayenne widget if I add it as a value and choose Inch as the unit, it doesn’t show me the correct value. I have added it using analog distance on virtual pin.
What’s Connected
- NodeMCU ESP 12-E
- HC-SR04
Triggers & Alerts
I built this and pointed the sensor to my door, so in the evening the moment I open my door after coming back from work the lights will switch on using trigger. I am sure there are other ways to do it like using a PIR sensor, but I had a HC-SR04 lying around and had to do some justice to it.
Dashboard Screenshots
##Code
// #define CAYENNE_DEBUG
#define CAYENNE_PRINT Serial
#include <ESP8266WiFi.h>
#include "CayenneDefines.h"
#include "BlynkSimpleEsp8266.h"
#include "CayenneWiFiClient.h"
#include "Ultrasonic.h"
#define VIRTUAL_PIN V2
#define TRIGGER 5
#define ECHO 4
// NodeMCU Pin D1 > TRIGGER | Pin D2 > ECHO
// Cayenne authentication token. This should be obtained from the Cayenne Dashboard.
char token[] = "xxxxxxx";
// Your network name and password.
char ssid[] = "xxxxxxx";
char password[] = "xxxxxxx";
Ultrasonic ultrasonic(5, 4);
void setup() {
Serial.begin (9600);
Cayenne.begin(token, ssid, password);
pinMode(TRIGGER, OUTPUT);
pinMode(ECHO, INPUT);
pinMode(BUILTIN_LED, OUTPUT);
}
void loop()
{
Cayenne.run();
// do something
}
// This function is called when the Cayenne widget requests data for the Virtual Pin.
CAYENNE_OUT(V2)
{
long duration;
int distance;
digitalWrite(TRIGGER, LOW);
delayMicroseconds(2);
digitalWrite(TRIGGER, HIGH);
delayMicroseconds(10);
digitalWrite(TRIGGER, LOW);
duration = pulseIn(ECHO, HIGH);
distance = ((duration/2) / 29.1) * 0.393701;
Serial.print(distance);
Serial.println("in");
delay(1);
Cayenne.virtualWrite(V2, distance);
}