control DC motor using pwm
Dependencies: Motordriver mbed
Fork of Motor_HelloWorld by
Diff: pwm-motor.cpp
- Revision:
- 1:a96dd8db5c11
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/pwm-motor.cpp Sun Dec 11 21:58:45 2016 +0000 @@ -0,0 +1,104 @@ +#include "mbed.h" +#include "motordriver.h" +#include "pwm-motor.h" + +static const char CLS[] = "\x1B[2J"; // VT100 erase screen +static const char HOME[] = "\x1B[H"; // VT100 home + +// in seconds +static const int move_delay = 0.02; + +enum Direction +{ + left, + right, +}; + +struct Movement +{ + public: + float start; + float stop; + float step; + float delay; + Direction direction; + + Movement() {} + + Movement(float startValue, + float stopValue, + float stepValue, + float delayValue, + Direction dir) : + start(startValue), + stop(stopValue), + step(stepValue), + delay(delayValue), + direction(dir) {} +}; + +Serial pc(USBTX, USBRX); + +int main() +{ + clear_screen(); + show_menu(); + + Motor motor(p21, p15, p17, 1); // PWM, Forward, Reverse, Can break + Movement leftMovement(-1.0, 1.0, 0.01, move_delay, left); + Movement rightMovement(1.0, -1.0, 0.01, move_delay, right); + + while (true) + { + Movement currentMovement; + switch(pc.getc()) + { + case 'r': + pc.printf("rotating right...\n\r"); + currentMovement = rightMovement; + move(motor, currentMovement); + break; + case 'l': + pc.printf("rotating left...\n\r"); + currentMovement = leftMovement; + move(motor, currentMovement); + break; + case 's': + pc.printf("stopping motor...\n\r"); + stop(motor); + break; + } + + } +} + +void clear_screen() +{ + pc.printf(CLS); + pc.printf(HOME); +} + +void show_menu() +{ + pc.printf("\rMotor controls:\n\r"); + pc.printf("l. Move left (counter-clockwise)\n\r"); + pc.printf("r. Move right (clockwise)\n\r"); + pc.printf("s. Stop\n\r"); +} + +void move(Motor& motor, Movement& movement) +{ + for (float s = movement.start; + movement.direction == left ? s < movement.stop : s > movement.stop; + movement.direction == left ? s += movement.step : s -= movement.step) + { + motor.speed(s); + wait(movement.delay); + } +} + + +void stop(Motor& motor) +{ + motor.stop(0.0); +} \ No newline at end of file