HC-SR04, Spark Core, Weird readings

Hi everybody,

I’m having some problems getting correct readings from a HC-SR04 ultrasonic sensor published via IFTTT to a google sheet. First we connected it all to an Arduino and it was not a problem to get correct values, but as soon as we connedted it to a Spark Core, copied the code to particle.io and published the variable, the readings came out very different and varying widely.

We did convert the float value to a string, in order to publish it.

Hope you guys can help me out :smile:

Regards Mads


//Defining pins
int trigPin = 4;
int echoPin = 2;


int delaytime = 100;  //delaytime between each dataset (milliseconds)

//Declaring variables for the users movement

float dist; //Initializing the variable to hold distance to user value.
String dist_pub;

void setup(){
	pinMode(trigPin, OUTPUT);
	pinMode(echoPin, INPUT);

void loop(){
	dist = dist_read();
	dist_pub = String(dist);
    Particle.publish("dist_pub", dist_pub);

// This function calculates the distance.
float dist_read(){
	//A function that reads the dist of the ultrasound sensor
	digitalWrite(trigPin, LOW);
	digitalWrite(trigPin, HIGH);
	digitalWrite(trigPin, LOW);

	//wait for the sound to come back to the sensor. The disance is calculated below in centimeters
	float tempDuration = pulseIn(echoPin, HIGH);
	float tempdist = (tempDuration/2) / 29.1;

	return tempdist;

You’ve connected the Vcc pin on the sensor board to VIN, not 3V3, on the Core right? The sensor requires 5V and the 4.8V that comes out of VIN when powering a Core or Photon by USB is probably close enough but 3V3 is definitely not.

Hi Rickkas7,

Yes - the Ultrasonic sensor is connected to the VIN, GND, D4 and D2.

Regards Mads

I don’t see anything wrong with your code, other than you’re publishing too often (you should adhere to the once per second limit). The 10 microseconds for the high trigger pulse is a minimum, you might want to try something a little longer (I use 15 microseconds in my code).

Hi Ric - thanks for your answer.

We figured out that the problem was not something in the code, but some converting bug between google sheets and particle, through IFTTT. We tried logging the values with other services and got the correct values.

Regards Mads