How to map water level sensor values to Percentage

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?

level = map (level, 0, 520, 0 , 100);

What does that mean?

Post the formatted vode in a code block.

Describe what the code actually does and how that differs from what you want.

Post a sample of the bogus output.

The basic idea is to match the sensor output with measured water levels and come up with a calibration formula, as described in this excellent tutorial: Why Calibrate? | Calibrating Sensors | Adafruit Learning System

//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.

When the sensor is dry, is the reading 0 (zero) or 1023?
When the sensor is fully submerged, is the reading 1023 or zero?

Maybe you need to map the percent "upside-down" like this...

level = map (level, 0, 1023, 100, 0);

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.