π¬ Distance Sensor
-
zboblamont . Thank you, I understand all of this except I really don't see in sketch testing of two consecutive results in X attempts. I see that node will wake up and update the distance if new data is different than old data, but, anyway, question was about something different. Why, single sensor node based on this example periodically generates 0 distance? Are there different models of these sensors, so NewPing library needs to be altered?
@apl2017 Verifying the reading is something you have to write into the sketch yourself, nothing complicated. I didn't use a library so no idea what advantage it brings over the simple timing method. Because I only take readings every hour triggered by an RTC, I don't care if it is the same as previous, only that it is valid in which case it is sent in.
Parts of my sketch follow, all fairly self-explanatory, perhaps they are of some use.
Main loop - Call subroutine and test to ensure it lies between two values, up to 10 attempts allowed to get a proper reading.while ((tankdepth<350||tankdepth>1000)&&counter<=10){//10 attempts to get proper range READULTRASONIC(); counter++; }The READULTRASONIC subroutine uses the simple timing method to get the 2 consecutive readings.
void READULTRASONIC(){//JSN-SR04-2.0 //Main loop checks valid range on a defined number of readings tankdepth=0; duration=0; distance=0; test=1; test2=3; // Normal range should lie between 389 and 989 absolutely empty is 1520 while (test!=test2){// Get two consecutive readings digitalWrite(Trigpin, LOW); delayMicroseconds(100); digitalWrite(Trigpin, HIGH); delayMicroseconds(150); digitalWrite(Trigpin, LOW); duration = pulseIn(Echopin, HIGH); distance = duration/5.82;//This is in mm if (test!=distance){ test=distance; distance=0; } else{ test2=distance; } delay(100);///// 500 originally but why??????? } tankdepth=distance; }There are many version of these sensors, neither of the two I trialled reliably ran unless on 5v, which made it bit more complicated for a 3.3v Node.
One operated on softserial from memory, but I couldn't get it to do what I wanted, I settled on the one which allows straightforward timing.When I was first testing these, the first reading would always be a zero for reasons unknown, then solid readings, but the 2 consecutive readings test worked for me.
-
@zboblamont Thanks, you are proposing to filter out wrong reading, I am trying to understand why system periodically sends out 0.
-
@zboblamont Thanks, you are proposing to filter out wrong reading, I am trying to understand why system periodically sends out 0.
@apl2017 Understood, good luck finding out whether environment, hardware, software, in isolation or combination are the cause.
As said previously, aside the leading zero, the arrangement and technique here returns stable readings, the only critical aspect found was need of a solid 5v.
The only anomaly found were a condensation drip on the sensor face at below -10 outside air temp, hence the 10 attempts limitation.
Good luck -
@APL2017 Did you find the reason for this problem of reading periodically 0cm?
I have the same problem with a Arduino Uno connected to a HC-SR04 sensor. (in reality I made two sensors and both have regularly 0cm as output)
I can blindly adapt the software to filter out these strange values, but like you, I prefer to understand why this behaviour? -
@APL2017 Did you find the reason for this problem of reading periodically 0cm?
I have the same problem with a Arduino Uno connected to a HC-SR04 sensor. (in reality I made two sensors and both have regularly 0cm as output)
I can blindly adapt the software to filter out these strange values, but like you, I prefer to understand why this behaviour?Maybe replying to myself : I read just in the sensor example:
int dist = metric?sonar.ping_cm():sonar.ping_in(); Serial.print("Ping: "); Serial.print(dist); // Convert ping time to distance in cm and print result (0 = outside set distance range) Serial.println(metric?" cm":" in");0 = outside set distance range
Good chance that this is the reason... -
@mfalkvidd Should we not adapt the example sketch to include this problem of returning a zero?
I did configure an automatisation in my controller when the distance was less than 10 cm, so it was fired regularly because 0cm was sent as message from the sensor node.
Change following code:if (dist != lastDist) { send(msg.set(dist)); lastDist = dist; }to
if (dist != lastDist && dist != 0) { send(msg.set(dist)); lastDist = dist; }The '0' means here that an error is fired inside the newping library, not that the distance is 0cm.
-
@mfalkvidd Should we not adapt the example sketch to include this problem of returning a zero?
I did configure an automatisation in my controller when the distance was less than 10 cm, so it was fired regularly because 0cm was sent as message from the sensor node.
Change following code:if (dist != lastDist) { send(msg.set(dist)); lastDist = dist; }to
if (dist != lastDist && dist != 0) { send(msg.set(dist)); lastDist = dist; }The '0' means here that an error is fired inside the newping library, not that the distance is 0cm.
-
@mfalkvidd Should we not adapt the example sketch to include this problem of returning a zero?
I did configure an automatisation in my controller when the distance was less than 10 cm, so it was fired regularly because 0cm was sent as message from the sensor node.
Change following code:if (dist != lastDist) { send(msg.set(dist)); lastDist = dist; }to
if (dist != lastDist && dist != 0) { send(msg.set(dist)); lastDist = dist; }The '0' means here that an error is fired inside the newping library, not that the distance is 0cm.
-
@mfalkvidd Should we not adapt the example sketch to include this problem of returning a zero?
I did configure an automatisation in my controller when the distance was less than 10 cm, so it was fired regularly because 0cm was sent as message from the sensor node.
Change following code:if (dist != lastDist) { send(msg.set(dist)); lastDist = dist; }to
if (dist != lastDist && dist != 0) { send(msg.set(dist)); lastDist = dist; }The '0' means here that an error is fired inside the newping library, not that the distance is 0cm.
@evb Having had various problems with two US devices using the ping library, found the simpler timing method gave consistent results after only an initial false.
Setting the upper and lower thresholds in the sketch (if that is appropriate - viz tanks) and checking for two consecutive readings within that over up to 10 attempts then validates the value, only then reporting the result. Converting the distance to mm is perhaps overkill, but for me it works 99.99% of the time. -
I did some research and the myssensors documentation should be updated...
@mfalkvidd I saw that you updated as latest person the example one year ago.
Maybe you could now mentioning the newer lib?The example is linking to an old legacy implementation of the NewPing library version 1.5.
This example uses the external NewPing library found here. Please install it and restart the Arduino IDE before trying to compile.
Better is to use the standard way in Arduino IDE to add the latest version of the NewPing library, now at version 1.9.1.
You can find information about this lib : https://bitbucket.org/teckel12/arduino-new-ping/wiki/HomeI changed the implementation to use the ping_median method provided by the lib author
sonar.ping_median(iterations [, max_cm_distance]) - Do multiple pings (default=5), discard out of range pings and return median in microseconds. [max_cm_distance] allows you to optionally set a new max distance.Using this method will discard out the spikes and out of ranges of the ultrasonic sensors.
/** * The MySensors Arduino library handles the wireless radio link and protocol * between your home built sensors/actuators and HA controller of choice. * The sensors forms a self healing radio network with optional repeaters. Each * repeater and gateway builds a routing tables in EEPROM which keeps track of the * network topology allowing messages to be routed to nodes. * * Created by Henrik Ekblad <henrik.ekblad@mysensors.org> * Copyright (C) 2013-2015 Sensnology AB * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors * * Documentation: http://www.mysensors.org * Support Forum: http://forum.mysensors.org * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 2 as published by the Free Software Foundation. * ******************************* * * REVISION HISTORY * Version 1.0 - Henrik EKblad * Version 1.1 - Eric Van Bocxlaer - Use of the ping_median method of the NewPing library * * DESCRIPTION * This sketch provides an example how to implement a distance sensor using HC-SR04 * http://www.mysensors.org/build/distance */ // Enable debug prints //#define MY_DEBUG //#define MY_DEBUG_VERBOSE_RFM69 #define MY_NODE_ID 1 // set the node ID manually because a MQTT gateway with Home Assistant as controller will not assign automatically a node Id - this must be set before the mysensors.h call // Enable and select radio type attached #define MY_RADIO_RFM69 #define MY_RFM69_FREQUENCY RFM69_868MHZ // Set your frequency here #define MY_IS_RFM69HW // Omit if your RFM is not "H" #define MY_RFM69_NEW_DRIVER //enable radio communication encryption //enable simple signing and encryption #define MY_SECURITY_SIMPLE_PASSWORD "my32bitpassword" #include <SPI.h> #include <MySensors.h> #include <NewPing.h> #define SENSOR_NAME "Distance Sensor" #define SENSOR_VERSION "1.1" #define CHILD_ID 1 // Each radio node can report data for up to 254 different child sensors. You are free to choose the child id yourself. // You should avoid using child-id 255 because it is used for things like sending in battery level and other (protocol internal) node specific information. #define TRIGGER_PIN 6 // Arduino pin tied to trigger pin on the ultrasonic sensor. #define ECHO_PIN 5 // Arduino pin tied to echo pin on the ultrasonic sensor. #define MAX_DISTANCE 300 // Maximum distance we want to ping for (in centimeters). Maximum sensor distance is rated at 400-500cm. unsigned long SLEEP_TIME = 30000; // Sleep time between reads (in milliseconds) NewPing sonar(TRIGGER_PIN, ECHO_PIN, MAX_DISTANCE); // NewPing setup of pins and maximum distance. MyMessage msg(CHILD_ID, V_DISTANCE); int lastDist; bool metric = true; void setup() { metric = getControllerConfig().isMetric; } void presentation() { // Send the sketch version information to the gateway and Controller sendSketchInfo(SENSOR_NAME, SENSOR_VERSION); // Register all sensors to gw (they will be created as child devices) by their ID and S_TYPE present(CHILD_ID, S_DISTANCE); } void loop() { // use the build-in digital filter to discard out of range pings int echoTime = sonar.ping_median(10); int dist = metric?sonar.convert_cm(echoTime):sonar.convert_in(echoTime); Serial.print("Ping: "); Serial.print(dist); Serial.println(metric?" cm":" in"); if (dist != lastDist) { send(msg.set(dist)); lastDist = dist; } sleep(SLEEP_TIME); }Pay attention that I use the RFM69 radio, so adapt this if you are using another radio.
Also disable signing and encryption if you don't use it (you should!)
Adapt sleep time if you want more than 2 readings per minute. -
@APL2017 Did you find the reason for this problem of reading periodically 0cm?
I have the same problem with a Arduino Uno connected to a HC-SR04 sensor. (in reality I made two sensors and both have regularly 0cm as output)
I can blindly adapt the software to filter out these strange values, but like you, I prefer to understand why this behaviour?