Learn how to use embedded RTOS (Beta version RTOS)

Dependencies:   mbed-rtos mbed

main.cpp

Committer:
leonardoaraujosantos
Date:
2015-09-03
Revision:
1:4d067c712d03
Parent:
0:5bd42710f2e7
Child:
2:daaf6b6ad568

File content as of revision 1:4d067c712d03:

#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 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;

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

    // Start a thread to togle the led
    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) {

    }
}