Important changes to repositories hosted on mbed.com
Mbed hosted mercurial repositories are deprecated and are due to be permanently deleted in July 2026.
To keep a copy of this software download the repository Zip archive or clone locally using Mercurial.
It is also possible to export all your personal repositories from the account settings page.
main.cpp
- Committer:
- markschwarzer
- Date:
- 2020-11-02
- Revision:
- 1:e1139c05dee9
- Parent:
- 0:60f29e7619ae
- Child:
- 2:d717847767b9
File content as of revision 1:e1139c05dee9:
//Mark Schwarzer Assignment 6 Part 1
#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) {
        if (switch_input==1, angle<180) {
            servo=angle+30.0;
            wait(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);
        }
    }
}