Niall Cunningham
/
ME30001_Lab01_Exercise_03b
3b
main.cpp
- Committer:
- NiallCunningham
- Date:
- 2016-09-23
- Revision:
- 0:79dc2fa0defa
File content as of revision 0:79dc2fa0defa:
#include "mbed.h" #include "Servo.h" #define NUMREADINGS 1000; AnalogIn A_In(p20); Serial pc(USBTX, USBRX); // USB serial interface Servo cr_srv(p21); // continuous rotation hobby servo Servo std_srv(p22); // standard hobby servo #define CR_SCALE 12.0 void init_servo() { // calibrate the servos for +/-5ms over +/-45deg cr_srv.calibrate(0.0005,45); std_srv.calibrate(0.0005,45); } int main() { float pos_val=0.5; // variable to hold position values float AIreadings=0.0; // variable to hold cummulative analouge values float cr_srv_cmd=0.5; // continuous rotation servo command value (range: 0.0 - 1.0) float std_srv_cmd=0.5; // standard servo command value (range: 0.0 - 1.0) // set the USB serial interface baud rate pc.baud(921600); init_servo(); while(1) { AIreadings = 0; for (int i=0; i<NUMREADINGS/2; i++) { AIreadings = AIreadings + A_in.read(); } for (int i=NUMREADINGS/2; i<NUMREADINGS; i++) { AIreadings = AIreadings + A_in.read(); } pos_val = AIreadings/NUMREADINGS; // use a sin function to create an oscillating servo postion with values // between 0.0 and 1.0 for the standard servo std_srv_cmd = sin(pos_val*2*3.14159)/2.0+0.5; // use a smaller scale for the continuous rotation servo, due to its limited sensitivity cr_srv_cmd = sin(pos_val*2*3.14159)/CR_SCALE+0.515; // sernd the servo command to the servos themselves cr_srv.write(cr_srv_cmd); // write to the continuous rotation servo std_srv.write(std_srv_cmd); // write to the standard servo // export the readings to a terminal program via the USB cable pc.printf("pos value: %6.4f, cr servo: %6.4f std servo: %6.4f\r", pos_val, cr_srv_cmd, std_srv_cmd); pos_val = pos_val + step_size; // increment/decrement the position if (pos_val > 1.0) pos_val = 0.0; // if the position is out of bounds, reset the pos value wait(0.250); // wait for 0.25s to give time for the display to show } }