Skip to content

Moving the robot

Slides

F for fullscreen · O for overview

Motor connection

motor connection

Motor A is the left motor and motor B is the right motor

Control motor

In controlling a motor, we are controlling the speed and direction of the motor. A motor can move at different speeds at either forward or backward direction.

The speed and direction of the motors are controlled by the following pins

Motor Parameter Pin
A speed 9
direction 2
B speed 5
direction 4
int SA = 9;
int DA = 2;
int SB = 5;
int DB = 4;

As we are controlling the motor by sending signal through the pins SA, SB, DA, DB, we need to set them as output.

pinMode(SA, OUTPUT);
pinMode(SB, OUTPUT);
pinMode(DA, OUTPUT);
pinMode(DB, OUTPUT);

To set motor A to move forward with roughly half speed, we can use

digitalWrite(DA, HIGH); //(1)
analogWrite(SA, 150);   //(2)

  1. Control direction of a motor

    digitalWrite(pin, level)
    

    • pin is the pin number of the motor direction
    • level is either HIGH (forward) or LOW (backward) to denote the direction of the motor
  2. Control speed of a motor

    analogWrite(pin, value)
    

    • pin is the pin number of the motor speed
    • value is a numerical value from 0 (stop) to 255 (full speed) to control the speed of the motor

We normally set the direction before setting the speed. This is to avoid the motor moving in unexpected direction when we give the speed.

Moving forward

int SA = 9;
int DA = 2;
int SB = 5;
int DB = 4;
void setup() {
  pinMode(SA, OUTPUT);
  pinMode(SB, OUTPUT);
  pinMode(DA, OUTPUT);
  pinMode(DB, OUTPUT);
}
void loop() {
  digitalWrite(DA, HIGH);
  analogWrite(SA, 150);
  digitalWrite(DB, HIGH);
  analogWrite(SB, 150);
}

Moving backward

The robot can be moved backward easily by changing the direction of the motors from HIGH to LOW

void loop() {
  digitalWrite(DA, LOW);
  analogWrite(SA, 150);
  digitalWrite(DB, LOW);
  analogWrite(SB, 150);
}

Combining forward and backward

As moving forward and backward are common actions for robot, we would create functions that we can call easily whenever we need them.

void moveForward() {
  digitalWrite(DA, HIGH);
  analogWrite(SA, 150);
  digitalWrite(DB, HIGH);
  analogWrite(SB, 150);
}
void moveBackward() {
  digitalWrite(DA, LOW);
  analogWrite(SA, 150);
  digitalWrite(DB, LOW);
  analogWrite(SB, 150);
}

After we have the moveForward and moveBackward functions, if we need the robot to move forward for 1 second and then move backward for 1 second, and repeat this process, we can

void loop() {
  moveForward();
  delay(1000);
  moveBackward();
  delay(1000);
}

Bring it further

  1. How do we stop the robot from moving?
  2. How do we turn left or right?
Three types of turning right