Software that generates a PWM signal that can make a servo motor move from one programmed position to another each time the user button of a Nucleo board is pressed.

Dependencies:   mbed

main.cpp

Committer:
YPROY
Date:
2017-03-08
Revision:
3:91070e0c0431
Parent:
2:7aacbdf39425

File content as of revision 3:91070e0c0431:

//This software is derived from the example Nucleo_pwm.
//It outputs a PWM signal that is compatible with Tower Pro SG90 servos.
//It makes the servo move from one programmed position to another each time the
//user button is pressed.
//The programmed positions are defined by the values that are stored in
//the variable "pulseDurationInMicroSeconds". 
//An index counter is used to select which value is to be used to set the pulse
//duration of the PWM signal that controls that servo.
//The value of this index counter is changed each time the user button is
//pressed and the changes are made in a way that makes the program repeatedly
//cycles through all the possible positions.
//It is just necessary to add values to "pulseDurationInMicroSeconds" to have
//the servo adopt more positions.

//Just connect the brown wire of a SG90 servo to GND, its red wire to AVDD and
//its the orange wire to D11 to have the SMT32-F401RE control the servo.
// 

#include "mbed.h"
#define NUMBER_OF_POSITIONS sizeof(pulseDurationInMicroSeconds)/sizeof(int)
#define PWM_PERIOD_FOR_SG90_IN_MS  20

DigitalOut userLED(LED1);
PwmOut towerProSG90(D11);
PwmOut testOutput(D10);
InterruptIn userButton(USER_BUTTON);
int index;
int pulseDurationInMicroSeconds[]=
//    {10, 1500, 1750, 2000, 1750, 1500, 10, 1500, 1250, 1000, 1250, 1500};
    {1500,1625,1750,1875,2000, 1875,1750,1625,1500,1375,1250,1125,1000,1125,1250,1375};    
//{700, 1550, 2500, 1550}
void responseToUserButtonPressed(void)
{
    index++;
    if (index >= NUMBER_OF_POSITIONS)
    {
        index = 0;
    }
    towerProSG90.pulsewidth_us(pulseDurationInMicroSeconds[index]);    
    testOutput.pulsewidth_us(20000 - pulseDurationInMicroSeconds[index]);
}

int main()
{
    index = 0;    
    towerProSG90.period_ms(PWM_PERIOD_FOR_SG90_IN_MS);
    towerProSG90.pulsewidth_us(pulseDurationInMicroSeconds[index]);
    testOutput.period_ms(PWM_PERIOD_FOR_SG90_IN_MS);
    testOutput.pulsewidth_us(20000 - pulseDurationInMicroSeconds[index]);
    userButton.fall(&responseToUserButtonPressed);
      
    while(1)
    {
        userLED = !userLED;
        wait(1);
    }
}