Devchannel Team
/
TestsRTOS
Learn how to use embedded RTOS (Beta version RTOS)
Diff: main.cpp
- Revision:
- 1:4d067c712d03
- Parent:
- 0:5bd42710f2e7
- Child:
- 2:daaf6b6ad568
--- a/main.cpp Thu Sep 03 00:06:32 2015 +0000 +++ b/main.cpp Thu Sep 03 22:11:03 2015 +0000 @@ -8,29 +8,99 @@ Serial serialIO(SERIAL_TX, SERIAL_RX); -DigitalOut led1(LED1); DigitalOut led2(LED2); +DigitalIn button(USER_BUTTON); + +// Some data queue +typedef struct { + float voltage; /* AD result of measured voltage */ + uint32_t counter; /* A counter value */ +} message_t; + +MemoryPool<message_t, 16> mpool; +Queue<message_t, 16> queue; + +// Mutex shared by threads that want's to use the serial port +Mutex stdio_mutex; + +void led_thread(void const *args) +{ + while (true) { + // Toogle led + led2 = !led2; + + // To avoid using the serial port at the same time by two threads use the mutex + stdio_mutex.lock(); + serialIO.printf("Toogle led2 from thread1 !\r\n"); + stdio_mutex.unlock(); + + // Put thread in wait state for 500ms + Thread::wait(500); + } +} + +void check_button(void const *args) +{ + while (true) { + // Read button + int butVal = button; -void led2_thread(void const *args) { + // To avoid using the serial port at the same time by two threads use the mutex + stdio_mutex.lock(); + serialIO.printf("Button state is:%d\r\n",butVal); + stdio_mutex.unlock(); + + // Put thread in wait state for 100ms + Thread::wait(100); + } +} + +void data_producer(void const *args) +{ + uint32_t i = 0; while (true) { - led2 = !led2; - Thread::wait(800); + i++; // fake data update + message_t *message = mpool.alloc(); + message->voltage = (i * 0.1) * 33; + message->counter = i; + queue.put(message); + Thread::wait(100); + } +} + +void data_consumer(void const *args) +{ + while(true) { + // Block until there is an event on the queue + osEvent evt = queue.get(); + if (evt.status == osEventMessage) { + message_t *message = (message_t*)evt.value.p; + + // Grab mutex to print data + stdio_mutex.lock(); + serialIO.printf("\nVoltage: %.2f V\n\r" , message->voltage); + serialIO.printf("Number of cycles: %u\n\r", message->counter); + stdio_mutex.unlock(); + + mpool.free(message); + } } } int main() -{ - int i = 1; +{ // Configure the serial speed. serialIO.baud(115200); - serialIO.printf("Learning Microcontrollers with mbed !\n"); - + serialIO.printf("Learning Microcontrollers with mbed !\r\n"); + // Start a thread to togle the led - Thread thread(led2_thread); + Thread thread_1(led_thread); + Thread thread_2(check_button); + Thread thread_3(data_producer); + Thread thread_4(data_consumer); + // Lock forever here... while(1) { - wait(1); - serialIO.printf("This program runs since %d seconds.\n", i++); - led1 = !led1; + } }