Hello,
I was going to do some minor automation. However, when I started my project, I got unexpected results. Then, I decided to test the performance of digital and analog inputs. To do this, I wrote this code (here, only for digital). The results are either always "HIGH" or a random combination of "HIGH" or "low" when no voltage is applied. When I test it at definite 5V or 0V, I get correct results. I already tried to exchange my Atmega 328 for my UNO, but results are still vey non-predictive.
Please suggest something. Already ran out of ideas.
#define LED 11 // the pin for the LED
#define BUTTON 7 // the input pin where the
// pushbutton is connected
int val = 0; // val will be used to store the state
// of the input pin
void setup() {
pinMode(LED, OUTPUT); // tell Arduino LED is an output
pinMode(BUTTON, INPUT);
Serial.begin (9600); // and BUTTON is an input
}
void loop(){
val = digitalRead(BUTTON); // read input value and store it
// check whether the input is HIGH (button pressed)
if (val == HIGH) {
analogWrite(LED, 50); // turn LED ON
Serial.println ("HIGH");
}
else {
analogWrite(LED, 0);
Serial.println ("low");
}
}