MailQueue.c 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #include "cmsis_os.h" // CMSIS RTOS header file
  2. /*----------------------------------------------------------------------------
  3. * Mail Queue creation & usage
  4. *---------------------------------------------------------------------------*/
  5. void Thread_MailQueue1 (void const *argument); // thread function 1
  6. void Thread_MailQueue2 (void const *argument); // thread function 2
  7. osThreadId tid_Thread_MailQueue1; // thread id 1
  8. osThreadId tid_Thread_MailQueue2; // thread id 2
  9. osThreadDef (Thread_MailQueue1, osPriorityNormal, 1, 0); // thread object 1
  10. osThreadDef (Thread_MailQueue2, osPriorityNormal, 1, 0); // thread object 2
  11. #define MAILQUEUE_OBJECTS 16 // number of Message Queue Objects
  12. typedef struct { // object data type
  13. uint8_t Buf[32];
  14. uint8_t Idx;
  15. } MAILQUEUE_OBJ_t;
  16. osMailQId qid_MailQueue; // mail queue id
  17. osMailQDef (MailQueue, MAILQUEUE_OBJECTS, MAILQUEUE_OBJ_t); // mail queue object
  18. int Init_MailQueue (void) {
  19. qid_MailQueue = osMailCreate (osMailQ(MailQueue), NULL); // create mail queue
  20. if (!qid_MailQueue) {
  21. ; // Mail Queue object not created, handle failure
  22. }
  23. tid_Thread_MailQueue1 = osThreadCreate (osThread(Thread_MailQueue1), NULL);
  24. if (!tid_Thread_MailQueue1) return(-1);
  25. tid_Thread_MailQueue2 = osThreadCreate (osThread(Thread_MailQueue2), NULL);
  26. if (!tid_Thread_MailQueue2) return(-1);
  27. return(0);
  28. }
  29. void Thread_MailQueue1 (void const *argument) {
  30. MAILQUEUE_OBJ_t *pMail = 0;
  31. while (1) {
  32. ; // Insert thread code here...
  33. pMail = osMailAlloc (qid_MailQueue, osWaitForever); // Allocate memory
  34. if (pMail) {
  35. pMail->Buf[0] = 0xff; // Set the mail content
  36. pMail->Idx = 0;
  37. osMailPut (qid_MailQueue, pMail); // Send Mail
  38. }
  39. osThreadYield (); // suspend thread
  40. }
  41. }
  42. void Thread_MailQueue2 (void const *argument) {
  43. MAILQUEUE_OBJ_t *pMail = 0;
  44. osEvent evt;
  45. while (1) {
  46. ; // Insert thread code here...
  47. evt = osMailGet (qid_MailQueue, osWaitForever); // wait for mail
  48. if (evt.status == osEventMail) {
  49. pMail = evt.value.p;
  50. if (pMail) {
  51. ; // process data
  52. osMailFree (qid_MailQueue, pMail); // free memory allocated for mail
  53. }
  54. }
  55. }
  56. }