How can I get this kit car forward then stop?

Hi, I'm a total newbie with arduino, but have been coding for about 2 semesters now, so I get most of the basics.

I've got my little arduino car kit and it run forward and backward fine.
Now I'm trying to get it to run for 5 seconds forward then stop, but I'm not quite sure how to set that up in my code.

This is what I have so far...

#include <Adafruit_MotorShield.h>

//create motor shield object and 4 motors
Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Adafruit_DCMotor *Motor1 = AFMS.getMotor(1);
Adafruit_DCMotor *Motor2 = AFMS.getMotor(2);
Adafruit_DCMotor *Motor3 = AFMS.getMotor(3);
Adafruit_DCMotor *Motor4 = AFMS.getMotor(4);

void setup()
{
  Serial.begin(9600);
  Serial.println("Riverbot DC Motor test!");

  //start the motor shield
  if (!AFMS.begin()) {
    Serial.println("Could not find Motor Shield. Check wiring");
    while (1);
  }
  Serial.println("Motor Shield found");

}

void loop()
{
    //set motor speed to 100 (max=255)
    Motor1->setSpeed(100);
    Motor2->setSpeed(100);
    Motor3->setSpeed(100);
    Motor4->setSpeed(100);

    Motor1->run(FORWARD);
    Motor2->run(FORWARD);
    Motor3->run(FORWARD);
    Motor4->run(FORWARD);
    delay(3000);
}

Do you know how to use millis to determine when 5 seconds have passed?

What happens when you set the delay() to 5000 and then Motor1->run(RELEASE), etc?

Ponder this code for a while:

bool expired;
unsigned long stopTime;

void setup() {
   pinMode(LED_BUILTIN, OUTPUT);
   digitalWrite(LED_BUILTIN, LOW);
   expired = false;
   stopTime = millis() + 5000;
}

void loop() {
   if( !expired  && millis() > stopTime ) {   
      digitalWrite(LED_BUILTIN, HIGH);
      expired = true;
   }
}
1 Like
#include <Adafruit_MotorShield.h>

//create motor shield object and 4 motors
Adafruit_MotorShield AFMS = Adafruit_MotorShield();
Adafruit_DCMotor *Motor1 = AFMS.getMotor(1);
Adafruit_DCMotor *Motor2 = AFMS.getMotor(2);
Adafruit_DCMotor *Motor3 = AFMS.getMotor(3);
Adafruit_DCMotor *Motor4 = AFMS.getMotor(4);

void setup(){
  Serial.begin(9600);
  Serial.println("Riverbot DC Motor test!");

  //start the motor shield
  if (!AFMS.begin()) {
    Serial.println("Could not find Motor Shield. Check wiring");
    while (1);
  }
  Serial.println("Motor Shield found");

    //set motor speed to 100 (max=255)
    Motor1->setSpeed(100);
    Motor2->setSpeed(100);
    Motor3->setSpeed(100);
    Motor4->setSpeed(100);
    Motor1->run(FORWARD);
    Motor2->run(FORWARD);
    Motor3->run(FORWARD);
    Motor4->run(FORWARD);
    delay(5000);
    Motor1->run(STOP);
    Motor2->run(STOP);
    Motor3->run(STOP);
    Motor4->run(STOP);
}

void loop(){}

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.