I'm working through the tutorial sketches at http://arduino.cc/en/Tutorial/HomePage and am stymied by the output in the serial monitor window, which looks like this:
on
number of button pushes: 1
off
on
number of button pushes: 2
off
on
number of button pushes: 3
off
on
number of button pushes: 4
off
on
number of button pushes: 5
off
This does not reflect the output of the Arduino itself, which begins with the LED on, turns it off after the first button push, and then turns it on whenever the total number of button pushes is a multiple of four.
I think the serial monitor output should look like this:
on
number of button pushes: 1
off
number of button pushes: 2
off
number of button pushes: 3
off
number of button pushes: 4
on
number of button pushes: 5
off
I transcribed the code by hand so I could trace out what each line did. When it didn't work correctly, I copied the code straight from the tutorial and got the same result. Here's the code:
const int buttonPin = 2; // the pin that the pushbutton is attached to
const int ledPin = 13; // the pin that the LED is attached to
int buttonPushCounter = 0; // counter for the number of button presses
int buttonState = 0; // current state of the button
int lastButtonState = 0; // previous state of the button
void setup() {
pinMode(buttonPin, INPUT);
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}
void loop() {
buttonState = digitalRead(buttonPin);
if (buttonState != lastButtonState) {
if (buttonState == HIGH) {
buttonPushCounter++;
Serial.println("on");
Serial.print("number of button pushes: ");
Serial.println(buttonPushCounter, DEC);
}
else {
Serial.println("off");
}
lastButtonState = buttonState;
}
if (buttonPushCounter % 4 == 0) {
digitalWrite(ledPin, HIGH);
} else {
digitalWrite(ledPin, LOW);
}
}
off
Any suggestions? I feel like I might have a set of curly braces that are not paired correctly in the "if else" section, but I'm not sure.
Also, because there is not an "else" to go with every "if", I am wondering if the "else" is paired with the wrong "if", but my eyes are getting bleary from studying it.