Hey, I’m looking to invert a value so when a distance/height is collected from a ultrasonic sensor, and a value is set for the desired height of the bath, it inverts it.
The scenario:
If the ultrasonic sensor was placed 40cm above the bath and a value/height was taken of 110cm (for example) that means the depth of the bathtub itself is 70cm (110 – 40). If a user wants the height of the bath to be 30cm (they will put in the value on a 2x16 LCD shield), I need an equation that will take that 30cm value (set by the user) and invert it so it’ll be 40cm, and add the other 40cm (distance between sensor and bathtub’s edge) to it, allowing the sensor to stop at 80cm, so the height of the bath water can be 30cm. However the height of the bath and the desired height always varies, is there a formula/ equation that could be implemented into my code:
(I’m using an Arduino Uno Rev 3)
#include <LiquidCrystal.h>
#define echoPin 2
#define trigPin 3
#define solenoidPin 11
LiquidCrystal lcd(8, 9, 4, 5, 6, 7);
int a = 0; //used for moving the cursor left or right.
byte numbr[4]; // This will hold 4 bytes, and if global, will init to all zeros
byte indx; //This will hold an index to the array. If global, it will init to 0
int enteredValue; // this will hold the final value entered
void setup() {
lcd.begin(16, 2);
lcd.setCursor(0,0);
lcd.print("Enter Height");
lcd.setCursor(0,1);
lcd.print("in cm:");
Serial.begin (9600);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(11, OUTPUT); // connected to S terminal of Relay
}
void loop() {
int x;
x = analogRead (0);
lcd.setCursor(a,1);
if (x < 60) {
//right button
if (indx < 3 ) {
indx++;
a++;
}
}
else if (x < 200) {
//up button
if (numbr[indx] < 90 ) {
numbr[indx]++;
lcd.setCursor(7,1);
lcd.print(numbr[indx]);
}
}
else if (x < 400){
//down button
if (numbr[indx] > 0 ) {
numbr[indx]--;
lcd.setCursor(7,1);
lcd.print(numbr[indx]);
}
}
else if (x < 600){
//left button
if (indx > 0) {
indx--;
a--;
}
}
else if (x < 800){
//want to use this to save the value and move onto another function.
enteredValue = 0;
for (int i = 0; i < 4; i++) {
enteredValue = (enteredValue * 10) + numbr[i];
lcd.clear();
lcd.setCursor(3,0);
lcd.print("Working...");
delay(50);
}
}
delay(100);
unsigned long duration, distance;
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance = (duration / 2) * 0.0344;
if (distance >= 200 || distance <= 5){
Serial.print("Distance = ");
Serial.println("Off");
digitalWrite(solenoidPin, LOW); // turn relay off
}
else {
Serial.print("Solenoid On Distance = ");
Serial.print(distance);
Serial.println(" cm");;
digitalWrite(solenoidPin, HIGH); // turn relay on
}
delay(500);