Sensors returning wrong values on Arduino. Why?

Hello,

I've built a simple watering bot to water a single plant pot, but I'm struggling with getting reliable readings from the water level float switch. Sometimes it just returns the wrong value, i.e. either low, when there's enough water, or high, when there isn't actually any water.

The setup consists of:
Arduino Nano
analog capacitive moisture sensor (in the earth)
digital water level float switch (in the water tank)
analog water level depth sensor (at the side of the plant pot to measure how much runover water there is)
5v pump controlled via PWM PIN
Transistor NIN 911
external 5v power supply

The float switch has two wires, one is connected to the ground, the other to digital pin 3 on the arduino.

Below is the sample code, for setting up that sensor and reading from it.

const int water_reservoir = 3;
int water_state; // HIGH/LOW

void setup() {
  Serial.begin(9600);      // open the serial port at 9600 bps:  
  pinMode(water_reservoir, INPUT);
}

void loop() { 
water_state = digitalRead(water_reservoir); 
Serial.print("water_state: ");
Serial.print(water_state);
}

The error is this:
When the water level is low, the sensor should return: 0, but sometimes it returns 1. Also when the water level is high, the sensor should return 1, but sometimes it returns 0.

If anyone could point me in a direction, why that sensor inconsistently returns it's state, that would be highly appreciated.

Kind regards

You need to use pinmode(water_reservoir, INPUT_PULLUP) to keep the input from floating.

The input will read HIGH unless the switch is closed.