My goal is to have an LED blink at a constant rate of 4 Hz and turn on for 1 second when the switch is pressed, following this one second the motor is supposed to turn in three seconds. I believe I have everything connected correctly and my code shows no errors but when connected the LED only glows constantly. Can anyone maybe find some bugs? Thanks.
/*----------------------------------------
LED/Switch/Motor program
------------------------------------------*/
define LED 2
define SWITCH 3
define MOTOR 4
void setup()
{
pinMode(LED,OUTPUT);
pinMode(SWITCH,INPUT);
digitalWrite(LED,LOW); // start with LED off
pinMode(MOTOR,OUTPUT);
pinMode(SWITCH,INPUT); // start with MOTOR off
digitalWrite(MOTOR,LOW);
}
void loop()
{
digitalWrite(2,HIGH); // pin 2 high (LED on)
delay(125); // wait 500 ms
digitalWrite(2,LOW); // pin 2 low (LED off)
delay(125); // wait 500 ms
digitalWrite(2,HIGH); // pin 2 high (LED on)
delay(125); // wait 500 ms
digitalWrite(2,LOW); // pin 2 low (LED off)
delay(125); // wait 500 ms
while (digitalRead(SWITCH) == HIGH)
{} // wait for button down
delay(10); // add time to debounce switch
while (digitalRead(SWITCH) == LOW)
{} // and wait for button up
digitalWrite(LED,HIGH); // turn LED on
while (digitalRead(SWITCH) == HIGH)
{} // wait for button down
delay(2000); // debounce
while (digitalRead(SWITCH) == LOW)
{} // and wait for button up
digitalWrite(LED,LOW); // turn LED off
while (digitalRead(SWITCH) == HIGH)
{} // wait for button down
delay(1010); // add time to debounce switch
while (digitalRead(SWITCH) == LOW)
{} // and wait for button up
digitalWrite(MOTOR,HIGH); // turn MOTOR on
while (digitalRead(SWITCH) == HIGH)
{} // wait for button down
delay(3000); // debounce
while (digitalRead(SWITCH) == LOW)
{} // and wait for button up
digitalWrite(MOTOR,LOW); // turn MOTOR off
} // repeat
Sorry, I thought I had adjusted all the side notes accordingly. The first piece of code should repeat when the circuit isn’t being affected by the switch. Therefore, the light should blink until the button is pressed and then flash for a second, the motor will spin for three and the blinking will resume at 4 Hz. Is there a way to separate these two functions more effectively?
There doesn't seem to be any code there to do what you say you're trying to do; it all seems to be waiting for you to press and release buttons before any action.
I suggest you look at the 'blink without delay' example sketch to understand how to make things happen at regular intervals. You would need to use this technique to make the LED flash, and also use it to make the flashing and the motor movement start and stop at the appropriate times.
Do you have a suitable motor shield and power supply to drive the motor? You'd better not be connecting it directly to the Arduino.