MsgQueue.c 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. mpid_MemPool2 = osMemoryPoolNew(MSGQUEUE_OBJECTS, sizeof(MSGQUEUE_OBJ_t), NULL);
  22. if (!mpid_MemPool2) {
  23. ; // MemPool object not created, handle failure
  24. }
  25. mid_MsgQueue = osMessageQueueNew(MSGQUEUE_OBJECTS, sizeof(MSGQUEUE_OBJ_t), NULL);
  26. if (!mid_MsgQueue) {
  27. ; // Message Queue object not created, handle failure
  28. }
  29. tid_Thread_MsgQueue1 = osThreadNew (Thread_MsgQueue1, NULL, NULL);
  30. if (!tid_Thread_MsgQueue1) return(-1);
  31. tid_Thread_MsgQueue2 = osThreadNew (Thread_MsgQueue2, NULL, NULL);
  32. if (!tid_Thread_MsgQueue2) return(-1);
  33. return(0);
  34. }
  35. void *Thread_MsgQueue1 (void *argument) {
  36. MEM_BLOCK_t *pMsg = 0;
  37. while (1) {
  38. ; // Insert thread code here...
  39. pMsg = (MEM_BLOCK_t *)osMemoryPoolAlloc (mpid_MemPool2, NULL); // get Mem Block
  40. if (pMsg) { // Mem Block was available
  41. pMsg->Buf[0] = 0x55; // do some work...
  42. pMsg->Idx = 0;
  43. osMessageQueuePut (mid_MsgQueue, &pMsg, NULL, NULL);
  44. }
  45. osThreadYield (); // suspend thread
  46. }
  47. }
  48. void *Thread_MsgQueue2 (void *argument) {
  49. osStatus_t status;
  50. MEM_BLOCK_t *pMsg = 0;
  51. while (1) {
  52. ; // Insert thread code here...
  53. status = osMessageQueueGet (mid_MsgQueue, &pMsg, NULL, NULL); // wait for message
  54. if (status == osOK) {
  55. if (pMsg) {
  56. ; // process data
  57. osMemoryPoolFree (mpid_MemPool2, pMsg); // free memory allocated for message
  58. }
  59. }
  60. }
  61. }