Buzzer keep beeping when sensor taken out
When sensor plugged in, everything working as expected
QUESTIONS:
Anything wrong with my code?
thanks
CODE:
// lowest and highest sensor readings:
const int sensorMin = 0; // sensor minimum
const int sensorMax = 1023; // sensor maximum
int led = 13; // The on-board Arduino LED
int buzzer = 13; // Output pin for Buzzer
void setup() {
pinMode(led, OUTPUT);
pinMode(buzzer, OUTPUT);
// initialize serial communication @ 9600 baud:
Serial.begin(9600);
}
void loop() {
// read the sensor on analog A0:
int sensorReading = analogRead(A0);
// map the sensor range (four options):
// ex: 'long int map(long int, long int, long int, long int, long int)'
int range = map(sensorReading, sensorMin, sensorMax, 0, 3);
// range value:
switch (range) {
case 0: // Sensor getting flood
Serial.println("Flood");
digitalWrite(buzzer, HIGH);
break;
case 1: // Sensor getting wet
Serial.println("Rain Warning");
digitalWrite(buzzer, LOW);
delay(1000);
tone(buzzer, 4000, 250);
break;
case 2: // Sensor dry
Serial.println("Not Raining");
digitalWrite(buzzer, LOW);
break;
}
delay(1); // delay between reads
}
When you just remove the sensor your code is reading an analog pin with nothing connected to it. It will get all sorts of random readings unless you have a pull-up or pull-down resistor connected to it (or use in the built-in INPUT_PULLUP mode).
BTW if you're really using the same pin for both buzzer and LED you don't need to set pinMode twice.
If I use Digital port 2 for Sensor Input, the Buzzer won't beep when I disconnect the sensor.
But it create new problem which is only No Rain or Rain state. It can't be Moderate Rain.
Moderate Rain can only be created using Analog Input
So I have to use Analog Input, because I want to have Moderate Rain.
Your suggestion is using INPUT_PULLUP.
But INPUT_PULLUP can only be used using Digital Input.
QUESTIONS:
Do you have sample using INPUT_PULLUP in Analog Input
Whether INPUT_PULLUP will work with analog inputs depends on whether the sensor can overcome the 30-50K Ohm resistance. Some can, but not all. I don't know about whatever your "Rain Sensor" is.
But it is a fact that if you keep reading an analog pin you will always get a value back from it which you have to take account of. So the real question is do you really need to disconnect the sensor? And if you must can you perhaps connect it via something like a 3.5mm switched socket that connects a resistor between pin and gnd (or 5V) when the sensor isn't plugged in?