MsgQueue.c 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. #include "cmsis_os2.h" // CMSIS RTOS header file
  2. /*----------------------------------------------------------------------------
  3. * Message Queue creation & usage
  4. *---------------------------------------------------------------------------*/
  5. void Thread_MsgQueue1 (void *argument); // thread function 1
  6. void Thread_MsgQueue2 (void *argument); // thread function 2
  7. osThreadId_t tid_Thread_MsgQueue1; // thread id 1
  8. osThreadId_t tid_Thread_MsgQueue2; // thread id 2
  9. #define MSGQUEUE_OBJECTS 16 // number of Message Queue Objects
  10. typedef struct { // object data type
  11. uint8_t Buf[32];
  12. uint8_t Idx;
  13. } MEM_BLOCK_t;
  14. typedef struct { // object data type
  15. uint8_t Buf[32];
  16. uint8_t Idx;
  17. } MSGQUEUE_OBJ_t;
  18. osMemoryPoolId_t mpid_MemPool2; // memory pool id
  19. osMessageQueueId_t mid_MsgQueue; // message queue id
  20. int Init_MsgQueue (void)
  21. {
  22. mpid_MemPool2 = osMemoryPoolNew(MSGQUEUE_OBJECTS, sizeof(MSGQUEUE_OBJ_t), NULL);
  23. if (!mpid_MemPool2) {
  24. ; // MemPool object not created, handle failure
  25. }
  26. mid_MsgQueue = osMessageQueueNew(MSGQUEUE_OBJECTS, sizeof(MSGQUEUE_OBJ_t), NULL);
  27. if (!mid_MsgQueue) {
  28. ; // Message Queue object not created, handle failure
  29. }
  30. tid_Thread_MsgQueue1 = osThreadNew (Thread_MsgQueue1, NULL, NULL);
  31. if (!tid_Thread_MsgQueue1) {
  32. return(-1);
  33. }
  34. tid_Thread_MsgQueue2 = osThreadNew (Thread_MsgQueue2, NULL, NULL);
  35. if (!tid_Thread_MsgQueue2) {
  36. return(-1);
  37. }
  38. return(0);
  39. }
  40. void Thread_MsgQueue1 (void *argument)
  41. {
  42. MEM_BLOCK_t *pMsg = 0;
  43. while (1) {
  44. ; // Insert thread code here...
  45. pMsg = (MEM_BLOCK_t *)osMemoryPoolAlloc (mpid_MemPool2, NULL); // get Mem Block
  46. if (pMsg) { // Mem Block was available
  47. pMsg->Buf[0] = 0x55; // do some work...
  48. pMsg->Idx = 0;
  49. osMessageQueuePut (mid_MsgQueue, &pMsg, NULL, NULL);
  50. }
  51. osThreadYield (); // suspend thread
  52. }
  53. }
  54. void Thread_MsgQueue2 (void *argument)
  55. {
  56. osStatus_t status;
  57. MEM_BLOCK_t *pMsg = 0;
  58. while (1) {
  59. ; // Insert thread code here...
  60. status = osMessageQueueGet (mid_MsgQueue, &pMsg, NULL, NULL); // wait for message
  61. if (status == osOK) {
  62. if (pMsg) {
  63. ; // process data
  64. osMemoryPoolFree (mpid_MemPool2, pMsg); // free memory allocated for message
  65. }
  66. }
  67. }
  68. }