8 years, 8 months ago.

How to control two independent servos?

Hello, I'm trying to operate two or more TowerPro MG995 servos using the PWM pins, all with period of 20 miliseconds, but I don't get how to write the code to control them independently at the same time. I have tried using Ticker, but just one of the PWM pins work. Here's my code:

  1. include "mbed.h"

void servo1(void); void servo2(void); void servo3(void); Ticker time_up; PwmOut PWM1(p21); PwmOut PWM2(p22); PwmOut PWM3(p23);

void servo1(){ PWM1.period(0.020); while (1) { PWM1=0.035; -90° wait(1); PWM1=0.05; -45° wait(1); PWM1=0.075; 0° wait(1); PWM1=0.1; 45° wait(1); PWM1=0.125; 90° wait(2); } }

void servo2(){ PWM2.period(0.020); while (1) { PWM2=0.125; -90° wait(1); PWM2=0.1; -45° wait(1); PWM2=0.075; 0° wait(1); PWM2=0.05; 45° wait(1); PWM2=0.035; 90° wait(2); } }

void servo3(){ PWM3.period(0.020); while (1) { PWM3=0.035; -90° wait(1); PWM3=0.05; -45° wait(1); PWM3=0.075; 0° wait(1); PWM3=0.1; 45° wait(1); PWM3=0.125; 90° wait(2); } }

int main() { time_up.attach(&servo2, 0.01); time_up.attach(&servo1, 0.01); time_up.attach(&servo3, 0.01); }

Be the first to answer this question.