Ultrasonic sensor with ESP8266

I am not sure if this is the right place to ask questions regarding problems I have encountered but I have searched everywhere on the internet and still can't get this to work.

I am trying to get data from the ultrasonic sensor using the ESP8266 and post it to google sheets.

The code I am using in Arduino IDE and the AppScript code is in this github link:

Code referred from: GitHub - StorageB/Google-Sheets-Logging: Log data from an ESP8266 device directly to Google Sheets without a third party service. Log sensor data, send data by pressing a button, and receive data from a Google spreadsheet. (NodeMCU, Wemos D1 mini, etc)

The hardware is connected as: 9V battery connected to buck converter to lower voltage to 5V, used to power HC-SR04 ultrasonic sensor. Trig pin connected to D2 of ESP8266 and Echo pin connected to D3 of ESP8266. The module is connected to Laptop, and is connected to my mobile hotspot.

Problems I am facing:
When I open Serial Monitor in the Arduino IDE,


Error while connecting

Percentage: 0% Distance: 0 cm Publishing data...

{"command": "insert_row", "sheet_name": "Sheet1", "values": "0,0"}

Error with request. Response status code: 0


This is what I get.
I tried to change the sensor, make sure the sensor is working using Arduino UNO, tested my power source, checked the ESP8266 module, looked at many other approaches, none of which have worked out. I am really at my wits end.
I humbly ask for help in solving this issue.

Thank you.

Can you post your sketch to look where this error originated?

{"command": "insert_row", "sheet_name": "Sheet1", "values": "0,0"}

Looks spreadsheet/database related.

1 Like

You can cross-check your code and circuit with this tutorial. And see if the error persists.

1 Like

If the code is exactly the same as the Github, that error message comes out at row 132 if the POST to the remote server has failed or refused, but can't say why.
Dump to serial not only the payload add also all other arguments like url and host, and check if your server is accepting requests (and see if the log shows you what it received and eventually denied the request).

I suspect you have also problems with the sensors, giving the message you posted "Percentage: 0% Distance: 0 cm": it's a typical SR04 behaviour when it stucks! In my experience SR04 are often faulty and unreliable, I threw them to trash years ago and successfully replaced them with SRF05 sensors, I won't ever buy SR04 again!!

PS: why the Serial Monitor output lines seem to be in reverse order?

1 Like

Yeah, I tried to post the data from the sensor into google spreadsheets.
The code for ESP8266 was:
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include "HTTPSRedirect.h"

//Ultrasonic sensor
#define Trig_pin 2
#define Echo_pin 3
#define MAX_DISTANCE 300

// Enter network credentials:
const char* ssid = "";
const char* password = "";

// Enter Google Script Deployment ID: CHANGE IF YOU CREATED NEW SPREADSHEET AND NEW DEPLOYMENT
const char *GScriptId = "AKfycbwtPs0ayulB02P2t3gbKtn_cZ1cBzy_khCVCTH5oTy8ByvmMLMjh72JNVCsIF0EDLtF-A";

// Enter command (insert_row or append_row) and your Google Sheets sheet name (default is Sheet1):
String payload_base = "{"command": "insert_row", "sheet_name": "Sheet1", "values": ";
String payload = "";

// Google Sheets setup (do not edit)
const char* host = "script.google.com";
const int httpsPort = 443;
const char* fingerprint = "";
String url = String("/macros/s/") + GScriptId + "/exec";
HTTPSRedirect* client = nullptr;

void setup() {

Serial.begin(9600);
pinMode(Trig_pin, OUTPUT);
pinMode(Echo_pin, INPUT);
digitalWrite(Trig_pin, LOW);
delay(10);
Serial.println('\n');

// Connect to WiFi
WiFi.begin(ssid, password);
Serial.print("Connecting to ");
Serial.print(ssid); Serial.println(" ...");

while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println('\n');
Serial.println("Connection established!");
Serial.print("IP address:\t");
Serial.println(WiFi.localIP());

// Use HTTPSRedirect class to create a new TLS connection
client = new HTTPSRedirect(httpsPort);
client->setInsecure();
client->setPrintResponseBody(true);
client->setContentTypeHeader("application/json");

Serial.print("Connecting to ");
Serial.println(host);

// Try to connect for a maximum of 5 times
bool flag = false;
for (int i=0; i<5; i++){
int retval = client->connect(host, httpsPort);
if (retval == 1){
flag = true;
Serial.println("Connected");
break;
}
else
Serial.println("Connection failed. Retrying...");
}
if (!flag){
Serial.print("Could not connect to server: ");
Serial.println(host);
return;
}
delete client; // delete HTTPSRedirect object
client = nullptr; // delete HTTPSRedirect object
}

void loop() {
long duration;
long distance;
int percentage;
digitalWrite(Trig_pin, HIGH);
delayMicroseconds(11);
digitalWrite(Trig_pin, LOW);
duration = pulseIn(Echo_pin, HIGH);
distance = duration * 0.034/2;
percentage = map(distance, 0, 25, 0, 100);
if(percentage < 0) {
percentage = 0;
}
else if(percentage > 100) {
percentage = 100;
}
Serial.print("Percentage: ");
Serial.print(percentage);
Serial.print("% Distance: ");
Serial.print(distance);
Serial.print(" cm");

static bool flag = false;
if (!flag){
client = new HTTPSRedirect(httpsPort);
client->setInsecure();
flag = true;
client->setPrintResponseBody(true);
client->setContentTypeHeader("application/json");
}
if (client != nullptr){
if (!client->connected()){
client->connect(host, httpsPort);
}
}
else{
Serial.println("Error creating client object!");
}

// Create json object string to send to Google Sheets
payload = payload_base + """ + distance + "," + percentage + ""}";

// Publish data to Google Sheets
Serial.println("Publishing data...");
Serial.println(payload);
if(client->POST(url, host, payload)){
// do stuff here if publish was successful
}
else{
// do stuff here if publish was not successful
Serial.println("Error while connecting");
}

// a delay of several seconds is required before publishing again
delay(5000);
}

Yeah! The sensor truly sucks! I will look into the SRF05 for my next project! I referred the original code from GitHub - StorageB/Google-Sheets-Logging: Log data from an ESP8266 device directly to Google Sheets without a third party service. Log sensor data, send data by pressing a button, and receive data from a Google spreadsheet. (NodeMCU, Wemos D1 mini, etc)
For the new attempt, I just added the ultrasonic sensor code for the ESP8266 sketch and the AppScript code. I got the posting to work. But, as you said, the sensor kept outputting distance as 0.

Finally, I looked up some sites which used the Arduino UNO as a power source for the sensor. Alas, the ESP8266 could not process the 5V pulses from the echo pin and the board heated up.

Serial monitor:
������E����T�T������D����������������������������������������G���M� ��������G���G

I would like to add that the blinking LED program still works, though I am not entirely sure if that is indicative of the health of the board.

Is this from the Uno? If so, and the board is not overheating, this is usually of a BAUD mismatch of your sketch (Serial.begin(9600)) and the IDE (lower-right, small numbers)

Well, years ago I wrote THIS library for me, to handle both SR04 and SRF05, if you set it up with "Sensor.Unlock = true;" some code activates as a workaround for the "locked" readings of SR04.
Give it a try, maybe you can keep your SR04 for the moment (but replace them asap...).

PS: sorry, the respository and docs are in italian, I'll soon plan to translate everything in english, but even if it's quite simple to understand how to use it, in the meanwhile you can still activate Google Translate...:wink:

EDIT: on GitHub I forgot there's a README_EN.txt file already with english description. Open it to read everything you need to know (even if the library has a very easy usage!)

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.