Learn how to use embedded RTOS (Beta version RTOS)

Dependencies:   mbed-rtos mbed

main.cpp

Committer:
leonardoaraujosantos
Date:
2015-09-03
Revision:
2:daaf6b6ad568
Parent:
1:4d067c712d03

File content as of revision 2:daaf6b6ad568:

#include "mbed.h"
#include "rtos.h"

//------------------------------------
// Serial configuration (Put on hyperterminal or Putty)
// 115200 bauds, 8-bit data, no parity
//------------------------------------

Serial serialIO(SERIAL_TX, SERIAL_RX);

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 toogleLed(void const *args)
{
    // Toogle led
    led2 = !led2;
}

void check_button(void const *args)
{
    while (true) {
        // Read button
        int butVal = button;

        // 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(300);
    }
}

void data_producer(void const *args)
{
    uint32_t i = 0;
    while (true) {
        i++; // fake data update
        message_t *message = mpool.alloc();
        message->voltage = (i * 0.1) * 33;
        message->counter = i;
        queue.put(message);
        Thread::wait(2000);
    }
}

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()
{
    // Configure the serial speed.
    serialIO.baud(115200);
    serialIO.printf("Learning Microcontrollers with mbed !\r\n");

    // Start a thread to togle the led    
    Thread thread_2(check_button);
    Thread thread_3(data_producer);
    Thread thread_4(data_consumer);
    
    // Periodically call a function
    RtosTimer timerTogLed(toogleLed, osTimerPeriodic);
    timerTogLed.start(1000);

    // Lock forever here...
    Thread::wait(osWaitForever);
}