Hello all,
The goal of my code is to press a button, run the DC motor for a specified amount of time, stop the motor, then return to the beginning of loop() and wait for a new button press. In the code provided, it seems like the code initialized the motor but does not want to enter the if statement to turn off the motor when the time has elapsed.
const int button_pin=2;
int button_state=0;
unsigned long previousMillis=0;
unsigned long currentMillis;
int lastButtonState=0;
void setup()
{
pinMode(7,OUTPUT);
pinMode(8,OUTPUT);
pinMode(10,OUTPUT);
pinMode(button_pin,INPUT);
Serial.begin(9600);
}
void loop() {
button_state=digitalRead(button_pin);
if (button_state == HIGH){
Serial.println("pressed");
DC_motor();
lastButtonState=button_state;
}
}
void DC_motor()
{
currentMillis = millis();
digitalWrite(8,HIGH);
digitalWrite(7,LOW);
analogWrite(10,100);
if((currentMillis-previousMillis)>=5000){
Serial.println("made it");
previousMillis=currentMillis;
digitalWrite(7,HIGH);
digitalWrite(8,HIGH);
Serial.println("now brake");
delay(1000);
loop();
}
}
armorall20:
The goal of my code is to press a button, run the DC motor for a specified amount of time, stop the motor, then return to the beginning of loop()
That's a flawed goal to start with. Let the loop() run (run loop, run!) as fast as possible. And just only act when you need to. Otherwise you can't do multiple things if you want to extend it. Now the use of millis() is just wasted and could be replaced with a delay() (which blocks execution of other code)...
The goal of my code is to press a button, run the DC motor for a specified amount of time, stop the motor, then return to the beginning of loop() and wait for a new button press.
The objective is OK but the method is flawed.
Save the value of millis() when the button becomes pressed, start the motor and set a boolean variable to true to flag that timing is taken place. Then, each time through loop() if timing is taking place check whether the required period has expired by subtracting the start time from teh current time. If it has expired then turn off the motor and set the timing variable to false. If the period has not expired then keep going round loop() until it has.
See Using millis() for timing. A beginners guide, Several things at the same time and look at the BlinkWithoutDelay example in the IDE.