Mark Schwarzer / Mbed 2 deprecated Schwarzer_A6_1

Dependencies:   mbed

main.cpp

Committer:
markschwarzer
Date:
2020-10-27
Revision:
0:60f29e7619ae
Child:
1:e1139c05dee9

File content as of revision 0:60f29e7619ae:

#include "mbed.h"

PwmOut servo(p20);
DigitalIn switch_input(p17);
DigitalOut led1(LED1);
DigitalOut led2(LED2);
DigitalOut led3(LED3);
DigitalOut led4(LED4);
Serial pc(USBTX,USBRX);
 
//Run through a range of pulse widths, report to serial output:
void servo_test(float period, float minPulse, float maxPulse, float pulseStep)
{
    float currentPulse;
    servo.period(period); //set the PWM period
 
    //Vary the pulse width from minimum to maximum in steps.
    pc.printf("Commencing Servo Test\r\n");
    for (currentPulse=minPulse; currentPulse<maxPulse; currentPulse=currentPulse+pulseStep) {
        servo.pulsewidth(currentPulse/1000000.000); //convert uSec to sec.
        pc.printf("Current pulse width is %f\r\n",currentPulse);
        wait(0.5);
    }
    pc.printf("Servo Test Finished\r\n");
}
 
 
//Sends correct pulse width to servo to achieve desired angle:
void servo_set_angle(float angle)
{
    float pulseCoeff = 10.0;
    float pulseOffset = 400;
    float pulseWidth;
 
    //Check to make sure commanded angle is within min-max bounds:
   
    if (angle == 0) {
        angle = 0;
        led1=1;
    } else if (0 < angle <= 90) {
        led2=1;
    }
    if (90 < angle < 180) {
        led3=1;
    } else if (angle == 180) {
        angle = 180.0;
        led4=1;
    }
 
    //Calculate pulsewidth for the desired angle and issue command:
    pulseWidth = pulseCoeff * angle + pulseOffset;
    servo.pulsewidth(pulseWidth/1000000.000);
}
 
int main()
{
    //Leave some time to get connection set up properly
    wait(3);
    //test servo from 0 to 5000 uSec, steps of 500
    servo_test(0.01,0,3000,50); 
    
    //cycle through angles, repeat:
    float angle;
    servo.period(0.01);
    
    while(1) {
        angle = 0;
        pc.printf("Test servo behavior here!");
        //Run through angles from 0 to 180 ad nauseum:
        for (angle=0.0; angle<180.0; angle=angle+10.0) {
            servo_set_angle(angle);
            pc.printf("Servo Angle: %5.2f\r\n",angle);
            wait(1);
        }
    }
}