RTOS application with 3 threads of different priorities: play music, measure temperature (and print results via stdio) and plays with the MMA8451Q sensor and the RGB LEDs

Dependencies:   MMA8451Q mbed-rtos mbed

main.cpp

Committer:
icserny
Date:
2016-01-28
Revision:
0:d3948113d6d9

File content as of revision 0:d3948113d6d9:

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

MMA8451Q acc(PTE25,PTE24,0x3A);             //SDA, SCL, I2C address lef shifted
PwmOut rled(LED_RED);                       //configure RGB LED pins as PWM outputs
PwmOut gled(LED_GREEN);
PwmOut bled(LED_BLUE);
PwmOut buzzer(D3);                          //used to play music

float frequency[]= {659,554,659,554,550,494,554,587,494,659,554,440}; //frequency array
uint8_t beat[]= {2,2,2,2,2,1,1,2,2,2,2,4};  //beat array

void music(void const *args)
{
    while (1) {
        for (int i=0; i<12; i++) {
            buzzer.period(1/frequency[i]);  // set PWM period
            buzzer=0.5;                     // set duty cycle
            Thread::wait(250*beat[i]);      // hold for beat period
        }
    }
}

void thermometer(void const *args)
{
    AnalogIn ain(A0);                       // Analog input at PTB0
    uint32_t mysum;                         // Used for summation

    printf("\r\nTask3: analog thermometer - with averaging\r\n");
    while(1) {
        mysum = 0;
        for(int i=0; i<3300; i++) {
            mysum += ain.read_u16();        // sum up raw 16-bit data
        }
        float voltage = mysum>>16;          // voltage in millivolts
        float tempC = (voltage -500)/10;    // tempereature in Celsius
        printf("voltage: %5.0f mV temp: %5.1f C\r\n",voltage,tempC);
        Thread::wait(2000);
    }
}


int main(void)
{
    Thread thread2(music);                  //Define a new task
    thread2.set_priority(osPriorityHigh);   //Give it high priority

    Thread thread3(thermometer);            //Define another new task
    thread3.set_priority(osPriorityLow);    //Give it high priority

    while (true) {                          //Run the default task
        float x, y, z;
        x = abs(acc.getAccX());             //Read X component of acceleration
        y = abs(acc.getAccY());             //Read Y component of acceleration
        z = abs(acc.getAccZ());             //Read Z component of acceleration
        rled = 1.0f - x;                    //Negative logic is used as the LEDs
        gled = 1.0f - y;                    //are of common anode type...
        bled = 1.0f - z;
        Thread::wait(100);                  //Time period is ~ 100 ms
    }
}