Hey Stefan, thank you for your detailed answer. Sorry for my slow reply. I've been swamped so haven't had time to respond until now. I understand the need to have a resistor between the input pin and the I previously had a resistor on my breadboard which is why I was using "pinMode(buttonPin, INPUT)". After understanding this post more and reading up on INPUT_PULLUP I simplified my wiring and I'm now using the internal pullup resistor.
This is the code I'm now attempting to use:
int motorPin = 9; //Define motor input pin
int buttonPin = 2; //Define button input pin
void setup() {
pinMode(motorPin, OUTPUT); //Set motorPin as an Output
pinMode(buttonPin, INPUT_PULLUP); //Set buttonPin as an Input
}
void loop() {
if (digitalRead(buttonPin) == LOW) { //When button is pressed
digitalWrite(motorPin, HIGH);
delay(3000); //run motor for 30000ms (3s)
digitalWrite(motorPin, LOW); //otherwise turn motor off
}
}
When I press my button it runs the motor, but the motor doesn't stop spinning after 3000ms.
I tried to use the serial monitor to understand what's happening, and it printed "1" then after another 3 seconds printed "1" again, so I suspect the button is somehow continuously being triggered. Admittedly, I don't fully understand how to implement the serial monitor so that information could be misleading.
Should I be using some other syntax instead of "digitalWrite(motorPin, LOW);" after my delay?
Here is the code I used when trying to use the serial monitor:
int motorPin = 9; //Define motor input pin
int buttonPin = 2; //Define button input pin
void setup() {
pinMode(motorPin, OUTPUT); //Set motorPin as an Output
pinMode(buttonPin, INPUT_PULLUP); //Set buttonPin as an Input
Serial.begin(9600); //Start serial monitor
}
void loop() {
if (digitalRead(buttonPin) == LOW) { //When button is pressed
digitalWrite(motorPin, HIGH);
Serial.println(digitalRead (motorPin), DEC);
delay(3000); //run motor for 30000ms (3s)
digitalWrite(motorPin, LOW); //otherwise turn motor off
}
}
Thanks for the help!