Example of using threads to run different actions happening at the same time.
Fork of Fa2018-es200-1121-3321-thread-example-rockem by
Diff: main.cpp
- Revision:
- 0:ed939452cce3
- Child:
- 2:2710cfd7bc6a
diff -r 000000000000 -r ed939452cce3 main.cpp --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/main.cpp Sun Oct 14 21:54:14 2018 +0000 @@ -0,0 +1,91 @@ +/* +ES200 Project 2 thread example +D Evangelista, 2018 +*/ + +#include "mbed.h" +#include "rtos.h" +#include "stdio.h" +#include "Motor.h" +#include "Servo.h" + +// Declare some stuff +DigitalIn sw1(p19); // switch for activating motor +DigitalIn sw2(p18); // switch for activating servo +DigitalOut led1(LED1); // status LED for sw1 +DigitalOut led2(LED2); // status LED for sw2 +DigitalOut heartbeat(LED4); // heartbeat LED +Motor m(p26,p30,p29); +Servo s1(p21); +Thread m_thread; // NEW IN mbed OS 5, threads are used to (sorta) do multiple things at once +Thread s1_thread; + +void m_callback(void); // This function will be run within the corresponding thread +void s1_callback(void); + +// main() runs in its own thread in the OS +int main() { + // startup things + printf("ES200 Project 2 thread example\n"); + s1.calibrate(0.0009,90.0); // calibrate servo s1 once at startup + m.speed(0.0); // set motor speed to zero at startup + + // start tasks + printf("main thread running\n"); + m_thread.start(callback(m_callback)); // starts the motor thread going + s1_thread.start(callback(s1_callback)); // starts the servo thread going + + // main loop + while(1){ + heartbeat = !heartbeat; // blink heartbeat once a second + ThisThread::sleep_for(1000); + + // I don't have to do my motor or servo stuff here because they are + // running in their own threads. + } // main loop +} // main() + + + + + +void m_callback(void){ + /** + Callback for executing a simple motor action. When sw1 is high, + the motor turns forward, otherwise the motor turns off. + */ + printf("m_thread running\n"); + while(1) { + if (sw1.read()){ + led1.write(1); // light a light for debugging purposes + m.speed(0.7); // spin motor ahead + } + else { + led1.write(0); + m.speed(0.0); // stop the shaft + } + ThisThread::sleep_for(200); // this thread executes 5x a second + } // while(1) +} // m_callback() + + + + +void s1_callback(void){ + /** + Simple callback for servo motion. When sw2 is high, the servo steps right, + otherwise it steps left. If it hits the ends it stays there. + */ + printf("s1_thread running\n"); + while(1){ + if (sw2.read()){ + led2.write(1); // light a light for debugging purposes + s1.write(s1.read()+0.1); // move servo a step to right + } + else{ + led2.write(0); + s1.write(s1.read()-0.1); // move servo a step to left + } + ThisThread::sleep_for(200); // this thread executes 5x a second + } // while(1) +} // s1_callback()