Skip to content

Micro servo for ultrasonic sensor

Slides

F for fullscreen · O for overview

What is a servo motor

Servo motor is a rotary actuator that allows precise rotational position. In the turtle robot, the servo motor is attached to the ultrasonic sensor to change the direction of the ultrasonic sensor

servo

How do we control a servo motor

servo cables

The position of the servo (angle) is controlled with the PWM signal.

45° 180° HIGH LOW 500µs 1000µs 2500µs min max 20ms

Set the servo pin to be output

1
2
3
4
int servopin = 3;
void setup() {
  pinMode(servopin, OUTPUT);
}

Create a function

To make it easier to send the command for the servo to rotate at the angle we want, we will create a function called servopulse.

void servopulse(int s_pin, int s_angle) {
} 

In the function servopulse, our purpose is to move the servo connected to s_pin to the angle s_angle

Calculate pulsewidth from angle Send the HIGH signal based on pulsewidth Send the LOW signal to complete 20ms cycle
void servopulse(int s_pin, int s_angle) {
  int pulsewidth = s_angle * 11 + 500;    //(1)
  digitalWrite(s_pin, HIGH);              //(2)
  delayMicroseconds(pulsewidth);
  digitalWrite(s_pin, LOW);               //(3)
  delay(20-pulsewidth/1000);
}
  1. Calculate pulsewidth

    Derivation of calculation for pulsewidth

    0

    500


    180

    2500

    angle

    pulsewidth

    \(\begin{aligned} \text{pulsewidth}-500 & = \frac{\text{angle}}{180}\times(2500-500)\\\\ \text{pulsewidth} & = \text{angle}\times\frac{2000}{180}+500\\\\ & \approx \text{angle}\times11 + 500 \end{aligned}\)

  2. Send HIGH signal

  3. Send LOW signal

Complete code

Here is the complete code to turn the servo to 90°

int servopin = 3;
void setup() {
  pinMode(servopin, OUTPUT);
}
void servopulse(int s_pin, int s_angle) {
  int pulsewidth = s_angle * 11 + 500;
  digitalWrite(s_pin, HIGH);
  delayMicroseconds(pulsewidth);
  digitalWrite(s_pin, LOW);
  delay(20-pulsewidth/1000);
}
void loop() {
  servopulse(servopin, 90);
}

If we want to check the calculation, we can use the serial monitor to display the values

int servopin = 3;
void setup() {
  pinMode(servopin, OUTPUT);
  Serial.begin(9600);
  Serial.println("servo program initiated");
}
void servopulse(int s_pin, int s_angle) {
  Serial.print("angle = ");
  Serial.print(s_angle);
  int pulsewidth = s_angle * 11 + 500;
  Serial.print(" pulsewidth = ");
  Serial.println(pulsewidth);
  digitalWrite(s_pin, HIGH);
  delayMicroseconds(pulsewidth);
  digitalWrite(s_pin, LOW);
  delay(20-pulsewidth/1000);
}
void loop() {
  servopulse(servopin, 90);
}