I’m trying out arduino and have programmed some button with a state switch. If it was “on” then it turns “off” and versa.
#include <Bounce.h>
const int buttonPin = 2;
const int ledPin = 6;
int ledState = HIGH;
int a = LOW;
int b = LOW;
Bounce push1 = Bounce( buttonPin,5 );
void setup() {
pinMode(buttonPin, INPUT);
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}
void loop() {
push1.update ( );
int x = digitalRead(push1.read());
if (x != b) {
if (x == HIGH) {
if (a == HIGH) {
a = LOW;
}
else {
a = HIGH;
}
}
else {
}
}
digitalWrite(ledPin, a);
Serial.println(a); // Weird thing
b = x;
}
It works well, but weird thing is that when i was programming i added some Serial prints to monitor output thru COM. Then after it all worked well i wanted to eliminate Serial.println(a); but it doesn’t work then!
The loop doesn’t respond to my button pressing at all.
Am I missing something? What could cause this kind of thing ?
Maybe i missed something, so fresh eye would be great : )
Thanks a lot!
You are reading the state of the button by calling
digitalRead(push1.read()).This is almost certainly incorrect (but I haven’t used the Bounce library).
push1.read()is reading the state of the button, presumably HIGH (0x1) or LOW (0x0). This button state value is then being used as the pin to read in the call todigitalRead. So, it looks to me like you are reading the state of either pin 0 or 1, not pin 2 where the button is. If I remember correctly pins 0 and 1 are the hardware serial port.Change:
to:
and see if that works better.
I suspect the
Serial.println(a)is a red-herring, it would certainly be acting as a delay. There may be a weird interaction happening between the serial port and your code as I believe you are reading the “button state” (x) from the serial port not the button.