NodeMCU Esp8266 + HC-SR04

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 :slight_smile:

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

  1. NodeMCU ESP 12-E
  2. 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


// #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(ECHO, INPUT);

void loop() 
  // do something

// This function is called when the Cayenne widget requests data for the Virtual Pin.


  long duration; 
  int distance;
  digitalWrite(TRIGGER, LOW);  
  digitalWrite(TRIGGER, HIGH);
  digitalWrite(TRIGGER, LOW);
  duration = pulseIn(ECHO, HIGH);
  distance = ((duration/2) / 29.1) *  0.393701;
  Cayenne.virtualWrite(V2, distance);


Hello good day, I’m having the same project with you. The only problem as to this time, I can’t even connect to Cayenne Dashboard. The hardware that I’m using are NodeMCU ESP8266, Arduino and HC-SR04 ultrasonic sensor. When I started to connect NodeMCU ESP8266 to cayenne dashboard using the Arduino IDE, I’ve got this error message “Leaving… Hard resetting via RTS pin”. Can anyone provide me a good solution about this problem. Thank you so much!

Ok thanks!