Arm Mbed and Pelion Device Management support forum

Need assistance with servo motor potentiometer setup

This code was supposed to move the servo motor when as the potentiometer turned, but for some reason, it doesn’t budge an inch. I am not sure if it is the program, the board, or my wiring. The board is a Nucleo STM L476RG board, and the servo is an SG90 micro servo motor and I was utilizing an imported copy of Jasper Denkers Servo library. If anyone could provide assistance that would be great.

#include "mbed.h"
#include "Servo.h"
#include "iostream"

Servo myservo(D6);
AnalogIn MyPot(A1);


int main() {
    float PotReading;
    PotReading = MyPot.read();

    while(1) {
     for(int i=0; i<100; i++) {
            myservo.SetPosition(PotReading);
            wait(0.01);
        }

        }
    }

Hi Jay,

Your code not working because:

  • you set the variable only once before the loop. The pot.read() must must be inside the loop or in a ticker if you want to change the value/PWM via the pot.
  • Also you miss information from the library. You need to read the Servo.h file where you can see on lines 30-50 an basic example how use this library. Or found a correct example of that library ServoTest. Or check the methods of that library, where you can found

Enable the servo. Without enabling the servo won’t be running.

  • Also you use a for cycle but not change the PotReading variable so you only 100 times set same value.

Edit:
Here you have a very basic example, what work with my servo, although it is not so smooth.

#include "mbed.h" //MbedOs 2
#include "Servo.h"

Servo servo(D10);
AnalogIn pot(D6);

int main() {
    servo.Enable(200,20000); // 200us start, period of 20ms in us
    while(1) {
        int value = 200+(pot.read()*2100);
        wait_ms(15);
        servo.SetPosition(value);
    }
}

BR, Jan