Simple example to use a Mail object in order to send complex messages from thread1 to thread2. Thread1 generates transition between random RGB colors and sends messages to Thread2. Thread2 displays the requested color on an RGB LED. Data items for messages are stored in a Mail object. Thread1 allocates mailbox slots, Thread2 should free up these slots after using up data stored in the slot.
main.cpp
- Committer:
- cspista
- Date:
- 2022-03-17
- Revision:
- 0:9f2b4b5956c0
File content as of revision 0:9f2b4b5956c0:
#include "mbed.h" #include "rtos.h" PwmOut rled(D3); PwmOut gled(D5); PwmOut bled(D6); DigitalOut led_common(D4); typedef struct { float red; float green; float blue; } message_t; Mail <message_t,4> mbox; //Mailbox for 4 messages void led_thread(void const *argument) { rled.period_ms(20); //Set period to 20 ms rled.write(1.0f); //Initialize to 0% duty cycle gled.period_ms(20); //Set period to 20 ms gled.write(1.0f); //Initialize to 0% duty cycle bled.period_ms(20); //Set period to 20 ms bled.write(1.0f); //Initialize to 0% duty cycle while (true) { osEvent evt = mbox.get(); //Wait for a message if(evt.status == osEventMail) { message_t *mymessage = (message_t*)evt.value.p; rled = 1.0f - mymessage->red; gled = 1.0f - mymessage->green; bled = 1.0f - mymessage->blue; mbox.free(mymessage); //Free up memory } } } float frand(void) { int32_t rv = 0x8000 -(rand()&0xFFFF); return (rv*rv/1073741824.0f); } int main (void) { float RGB1[3]; float RGB2[3]; float INC[3]; led_common = 1; // for commono anode... Thread thread2(led_thread); //--- Create a random color --------------------- for (int x=0; x<3; x++) { RGB1[x] = frand(); } while (true) { //--- Create a new random color ----------------- for (int x=0; x<3; x++) { RGB2[x] = frand(); } //--- Determine increments to go from color 1 to color 2 in 25 steps for (int x=0; x<3; x++) { INC[x] = (RGB1[x] - RGB2[x]) / 25; } //--- Send color codes to thread2 --------------- for (int s=0; s<25; s++) { message_t *message = mbox.alloc(); //Allocate memory message->red = RGB1[0]; message->green = RGB1[1]; message->blue = RGB1[2]; mbox.put(message); //Send data as message Thread::wait(100); for (int x=0; x<3; x++) { RGB1[x] -= INC[x]; //Approach to second colour } } } }