MsgQueue.c 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #include "cmsis_os.h" // CMSIS RTOS header file
  2. /*----------------------------------------------------------------------------
  3. * Message Queue creation & usage
  4. *---------------------------------------------------------------------------*/
  5. void Thread_MsgQueue1 (void const *argument); // thread function 1
  6. void Thread_MsgQueue2 (void const *argument); // thread function 2
  7. osThreadId tid_Thread_MsgQueue1; // thread id 1
  8. osThreadId tid_Thread_MsgQueue2; // thread id 2
  9. osThreadDef (Thread_MsgQueue1, osPriorityNormal, 1, 0); // thread object 1
  10. osThreadDef (Thread_MsgQueue2, osPriorityNormal, 1, 0); // thread object 2
  11. #define MSGQUEUE_OBJECTS 16 // number of Message Queue Objects
  12. typedef struct { // object data type
  13. uint8_t Buf[32];
  14. uint8_t Idx;
  15. } MEM_BLOCK_t;
  16. typedef struct { // object data type
  17. uint8_t Buf[32];
  18. uint8_t Idx;
  19. } MSGQUEUE_OBJ_t;
  20. osPoolId mpid_MemPool2; // memory pool id
  21. osPoolDef (MemPool2, MSGQUEUE_OBJECTS, MEM_BLOCK_t); // memory pool object
  22. osMessageQId mid_MsgQueue; // message queue id
  23. osMessageQDef (MsgQueue, MSGQUEUE_OBJECTS, MSGQUEUE_OBJ_t); // message queue object
  24. int Init_MsgQueue (void) {
  25. mpid_MemPool2 = osPoolCreate (osPool (MemPool2)); // create Mem Pool
  26. if (!mpid_MemPool2) {
  27. ; // MemPool object not created, handle failure
  28. }
  29. mid_MsgQueue = osMessageCreate (osMessageQ(MsgQueue), NULL); // create msg queue
  30. if (!mid_MsgQueue) {
  31. ; // Message Queue object not created, handle failure
  32. }
  33. tid_Thread_MsgQueue1 = osThreadCreate (osThread(Thread_MsgQueue1), NULL);
  34. if (!tid_Thread_MsgQueue1) return(-1);
  35. tid_Thread_MsgQueue2 = osThreadCreate (osThread(Thread_MsgQueue2), NULL);
  36. if (!tid_Thread_MsgQueue2) return(-1);
  37. return(0);
  38. }
  39. void Thread_MsgQueue1 (void const *argument) {
  40. MEM_BLOCK_t *pMsg = 0;
  41. while (1) {
  42. ; // Insert thread code here...
  43. pMsg = (MEM_BLOCK_t *)osPoolCAlloc (mpid_MemPool2); // get Mem Block
  44. if (pMsg) { // Mem Block was available
  45. pMsg->Buf[0] = 0x55; // do some work...
  46. pMsg->Idx = 0;
  47. osMessagePut (mid_MsgQueue, (uint32_t)pMsg, osWaitForever); // Send Message
  48. }
  49. osThreadYield (); // suspend thread
  50. }
  51. }
  52. void Thread_MsgQueue2 (void const *argument) {
  53. osEvent evt;
  54. MEM_BLOCK_t *pMsg = 0;
  55. while (1) {
  56. ; // Insert thread code here...
  57. evt = osMessageGet (mid_MsgQueue, osWaitForever); // wait for message
  58. if (evt.status == osEventMessage) {
  59. pMsg = evt.value.p;
  60. if (pMsg) {
  61. ; // process data
  62. osPoolFree (mpid_MemPool2, pMsg); // free memory allocated for message
  63. }
  64. }
  65. }
  66. }