I’m not sure if my issue is firmware-related or hardware-related, so I may be posting this in the wrong place.
I have an app (running on a Photon) that monitors the level of water in a storage tank using a JSN-SR04T ultrasonic sensor and Tim Eckel’s New_Ping library. For some reason that I cannot figure out, my code - below - results in water level measurements that alternate back and forth between two values even when the water level hasn’t changed. I’ve attached a screenshot of the event log that shows a sample of the alternating values. Note that the built-in functions for querying the height and gallons between scheduled events often return different values than the scheduled events do. Note, also, that the “-1” value for gallons associated with the higher height value is a result of exceeding the dimension of the associated array; that’s not my current concern.
Does anyone with JSN-SR04T experience have any thoughts about why this is happening and how to fix it, i.e. how to generate consistent values?
// This #include statement was automatically added by the Particle IDE.
#include <New_Ping.h>
// Define variables:
int gallons;
int distance; // Distance from sensor to top of water
int height; // Height of water in the tank
int gap = 7; // Distance between sensor and maximum water level
int Alert = 1;
#define trigPin 2 // 10 on breadboard
#define echoPin 3 // 9 on breadboard
#define MAX_DISTANCE 400
NewPing sonar = NewPing(trigPin, echoPin, MAX_DISTANCE);
void setup() {
Particle.function("Gallons", getGallons);
Particle.function("Inches", getInches);
}
int depth [67] = {919,905,891,877,863,849,836,822,808,794,780,766,752,738,724,710,696,682,668,654,641,627,613,599,585,571,557,543,529,515,501,487,473,460,446,432,418,404,390,376,362,348,334,320,306,292,279,265,251,237,223,209,195,181,167,153,139,125,111,97,84,70,56,42,28,14,0};
// Function to retrieve gallons
int getGallons(String command) {
distance = sonar.ping_in(); // Inches to top of water
distance = distance - gap; // Adjust for air gap between top of water and sensor
gallons = depth [distance];
return gallons;
} // End getGallons Function
// Function to retrieve height
int getInches(String command) {
distance = sonar.ping_in(); // Inches to top of water
distance = distance - gap; // Adjust for air gap between top of water and sensor
height = 67 - distance; // Inches above bottom of tank
return height;
} // End getInches Function
void loop() {
distance = sonar.ping_in();// Inches to top of water
distance = distance - gap;
height = 67 - distance ; // // Inches above bottom of tank
gallons = depth [distance];
Particle.publish ("Gallons",String(gallons),60, PRIVATE);
Particle.publish ("Height",String(height),60, PRIVATE);
if (gallons < 500){
Particle.publish ("Alert", String(Alert), PRIVATE);
}
delay(60000); // Take a measurement every minute
}