I want to use a button as on/off switch so when i press the button the motor should start spinning. when ever i press the button again it should stop spinning. I used the example StateChangeDetection. but right now it doesnt work. could someone help me?
Thanks for your time.
const int buttonPin = 2;
int buttonPushCounter = 0;
int buttonState = 0;
int lastButtonState = 0;
int motor1pin1 = 0;
int motor1pin2 = 0;
void setup() {
// put your setup code here, to run once:
pinMode (buttonPin, INPUT);
pinMode (motor1pin1, OUTPUT);
pinMode (motor1pin2, OUTPUT);
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
buttonState = digitalRead(buttonPin);
if (buttonState != lastButtonState) {
if (buttonState == HIGH) {
buttonPushCounter++;
Serial.println("on");
Serial.print ("1:");
Serial.println(buttonPushCounter);
} else {
Serial.println("off");
}
delay (50);
}
lastButtonState = buttonState;
if (buttonPushCounter % 1 == 0) {
digitalWrite (motor1pin1, HIGH);
digitalWrite (motor1pin2, LOW);
} else {
digitalWrite (motor1pin1, LOW);
digitalWrite (motor1pin2, LOW);
}
}
Forget the pushbuttons for now and write a small sketch that drives the motor in one direction for 5 seconds then in reverse for 5 seconds then repeats