I built circuit #7 on the top part of the breadboard and circuit #3 on the bottom part using this sketch
Code: Select all
#include <SoftwareSerial.h>
/*
Button
Turns on and off a light emitting diode(LED) connected to digital
pin 13, when pressing a pushbutton attached to pin 2.
The circuit:
* LED attached from pin 13 to ground
* pushbutton attached to pin 2 from +5V
* 10K resistor attached to pin 2 from ground
http://www.arduino.cc/en/Tutorial/Button
*/
// constants won't change. They're used here to set pin numbers:
const int buttonPin1 = 2; // the number of the pushbutton pin
const int buttonPin2 = 3; // the number of the pushbutton pin
const int ledPin = 13; // the number of the LED pin
const int motorPin = 9; // define the pin the motor is connected to (if you use pin 9,10,11 or 3 you can also control speed)
int buttonState = digitalRead(buttonPin1);
void setup() {
pinMode(ledPin, OUTPUT); // initialize the LED pin as an output:
pinMode(buttonPin1, INPUT); // initialize the pushbutton pin as an input
pinMode(buttonPin2, INPUT); // initialize the pushbutton pin as an input
pinMode(motorPin, OUTPUT);
Serial.begin(9600);
}
void loop() {
int buttonState = digitalRead(buttonPin1);
if (digitalRead(buttonPin1) == LOW) { // check if the pushbutton is pressed. if it is, the buttonState is LOW
digitalWrite(ledPin, HIGH); // turn LED on:
digitalWrite(motorPin, HIGH); // turns the motor On
Serial.println(buttonState);
}
else if(digitalRead(buttonPin2) == LOW) { // check if the pushbutton is pressed. if it is, the buttonState is LOW
digitalWrite(ledPin, LOW); // turn LED off
digitalWrite(motorPin, LOW); // turns the motor Off
Serial.println(buttonState);
}
}
https://plus.google.com/photos/10699157 ... kY3jx8OPVg
When I press Button 1 (buttonPin1) the LED turns on and the motor starts turning and I get a series of 0s for the buttonState on the Serial Monitor only while I have the button pressed. As soon as I let off the button the LED turns off, the motor stops turning and I get a value of one for buttonState on the Serial Monitor. If I load the sketch for circuit #3 the motor functions as expected, turning on then off. If I load the sketch for circuit #7 with additional code for the Serial Monitor output everything functions as it should, when I press Button 1 the LED turns on and I get a value of 0 on the Serial Monitor and when I press Button 2 (buttonPin2) the LED turns off and I get a value of 1 on the Serial Monitor.
So why doesn't it work when I used the combined sketch? Does it have to do with button bounce? If not where am I going wrong?
TIA,
Paul