I have a sketch set up to run switch case statement base on voltage of a potentiometer. I have it set so case 0 has an if statement to light up LED's if the button is pressed. For some reason the LED flicker on every 6 seconds or so and then turn back off even when nothing is attached to A5(the pin going to the button). If I change the potentiometer to the highest voltage the LEDS don't light up. I am not sure how it is getting an analog reading even when no cable is plugged into the A5 pin. Also, when the LEDs are off I can push the button and they turn on, as soon as I let got they turn off again. This is very odd, any ideas?
Here is the code
const int sensorMin = 0; // sensor minimum, discovered through experiment
const int sensorMax = 1023; // sensor maximum, discovered through experiment
const int pentometerPin = A0;// pin that the pentometer is attached to
const int buttonApin = A5; // pin that the button is attached to
const int ledPin = 8;
const int ledPin2 = 9;
void setup() {
pinMode(ledPin, OUTPUT);
pinMode(ledPin2, OUTPUT);
pinMode(buttonApin, INPUT);
// initialize serial communication:
Serial.begin(9600);
}
void loop() {
// read the sensor:
int sensorReading = analogRead(A0);
int buttonstate = analogRead(buttonApin);
// map the sensor range to a range of four options:
int range = map(sensorReading, sensorMin, sensorMax, 0, 6);
// do something different depending on the
// range value:
switch (range) {
case 0:
if(buttonstate == LOW)
{
digitalWrite(ledPin, HIGH);
digitalWrite(ledPin2, HIGH);
Serial.println("Button Pressed");
}
else
{
digitalWrite(ledPin, LOW);
digitalWrite(ledPin2, LOW);
}
// your hand is on the sensor
Serial.println("lowest");
break;
case 1: // your hand is close to the sensor
Serial.println("lower");
break;
case 2: // your hand is a few inches from the sensor
Serial.println("low");
break;
case 3: // your hand is nowhere near the sensor
Serial.println("medium");
break;
case 4:
Serial.println("high");
break;
case 5:
Serial.println("higher");
break;
case 6:
Serial.println("highest");
break;
}
delay(1); // delay in between reads for stability
}
Here is the layout: 1 item