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
How do we control a servo motor
The position of the servo (angle) is controlled with the PWM signal.
Set the servo pin to be 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
.
In the function servopulse
, our purpose is to move the servo connected to s_pin
to the angle s_angle
-
Calculate pulsewidth
Derivation of calculation for pulsewidth
0
500
180
2500
angle
pulsewidth
-
Send HIGH signal
- 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);
}