I am following this tutorial here and I have the sensor saying low, medium, high. However, I am trying to use the map() function to map the values 0-520 on 0-100, but it is not working correctly. How can I map these values properly to get an accurate percentage?
//Arduino water level sensor code
// Sensor pins pin 3 power output, pin A0 analog Input
#define sensorPin A0
#define sensorPower 3
float percentage; //variable to store percentage
float val = 0; // Value for storing water level
void setup() {
// Set D3 as an OUTPUT
pinMode(sensorPower, OUTPUT);
// Set to LOW so no power flows through the sensor
digitalWrite(sensorPower, LOW);
Serial.begin(9600);
}
void loop()
{
int level = readSensor();
level = map (level, 0, 520, 0 , 100);
Serial.print("Water level: ");
Serial.print(level);
Serial.println("%");
delay(1000); //1 sec delay
}
//This is a function used to get the reading
int readSensor() {
digitalWrite(sensorPower, HIGH); // Turn the sensor ON
delay(10); // wait 10 milliseconds
val = analogRead(sensorPin); // Read the analog value form sensor
digitalWrite(sensorPower, LOW); // Turn the sensor OFF
return val; // send current reading
}
This is my code. I am trying to map the water level into a percentage. The reason I am saying it is not working the way I want it to is I'll put the sensor roughly 25% in and the percentage in the serial monitor will say 75%.
I also tried using
level = map (level, 0, 1023, 0 , 100);
that gave me more of what I want, the sensor is halfway in and it will say 50% and when it is 25% in it will say 25%. It will cap at 50% though because 1023 is too high and the max the sensor goes to is 520.
I hope that makes sense. If you need further information let me know.