Hi all this is my first post on here but I have been following posts for a while.
my question is how do I make my ultrasonic sensors measure within a range I.e my sketch measures in percentage and i would like it to measure from 100% to 0% on tank1 and from 0% to 100% on the other
and only measure within that range. How can i achieve this please.
//Distance measure in cm converts to persentage
#include <NewPing.h>
const int trigPin1 = 6; //Trigger pin for sensor 1.
const int echoPin1 = 7; //Echo pin for sensor 1
const int trigPin2 = 8; //Trigger pin for sensor 2
const int echoPin2 = 9; //Echo pin for sensor 2
int pause1 = 5; //5 millsecond delay
int pause2 = 10; //10 millisecond delay
int Distance, Distance2, Duration, Duration2, percentage, percentage2;
int TankDepth1 = 26; // put your tank 1 depth here.
int TankDepth2 = 20; // put your tamkk 2 depth here.
const int MAX_DISTANCE = 30;
NewPing Sonar1 (trigPin1, echoPin1, MAX_DISTANCE);
NewPing Sonar2 (trigPin2, echoPin2, MAX_DISTANCE);
void setup() {
pinMode (trigPin1, OUTPUT); //Trigger pin 1 output
pinMode (echoPin1, INPUT); //Echo pin 1 input
pinMode (trigPin2, OUTPUT); //Trigger pin 2 output
pinMode (echoPin2, INPUT); //Echo pin 2 input
Serial.begin(9600);
}
void loop() {
digitalWrite (trigPin1, LOW); //Trigger pin 1 low
delay(pause1);
digitalWrite (trigPin1, HIGH); //Trigger pin 1 high
delay(pause2);
digitalWrite (trigPin1, LOW); //Trigger pin 1 low
Duration = pulseIn(echoPin1, HIGH);
Distance = Duration * 0.034/2; //convert duration to distance in cm
percentage = (100*Distance/TankDepth1); //convert distance to percent
percentage = 100 - percentage; // makes the percentage 100-0
digitalWrite (trigPin2, LOW); //
delay(pause1);
digitalWrite (trigPin2, HIGH);
delay(pause2);
digitalWrite (trigPin2, LOW);
Duration2 = pulseIn(echoPin2, HIGH);
Distance2 = Duration2 * 0.034/2;
percentage2 = (100*Distance/TankDepth2);
Serial.print ("TANK1 ");
Serial.print (percentage);
Serial.println ( "%");
delay(1000);
Serial.println();
Serial.print ("TANK2 ");
Serial.print (percentage2);
Serial.println ( "%");
Serial.println();
delay(1000);
}