Arduino Serial.println weird bug

2019-09-05 05:57发布

问题:

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!

回答1:

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 to digitalRead. 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:

int x = digitalRead(push1.read());

to:

int x = push1.read();

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.



回答2:

mttrb is correct in that

int x = digitalRead(push1.read());

is the source of the problem. One can see in on Arduino's web page of the library and its example may be initially miss leading.

digitalWrite(LED, bouncer.read());

It is worth noting though the

int x = push1.read();

As per the library code is simply a periodic read of the digitalread(buttonPin); Not much real benefit. Where it is usually more beneficial to

if (push1.fallingEdge()) {
...

Noting that falling/risingEdge() functions are stateful, and these member functions clear the statechange. So that new edges are correspondingly flagged for reading.