MemPool.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #include "cmsis_os2.h" // CMSIS RTOS header file
  2. /*----------------------------------------------------------------------------
  3. * Memory Pool creation & usage
  4. *---------------------------------------------------------------------------*/
  5. #define MEMPOOL_OBJECTS 16 // number of Memory Pool Objects
  6. typedef struct { // object data type
  7. uint8_t Buf[32];
  8. uint8_t Idx;
  9. } MEM_BLOCK_t;
  10. osMemoryPoolId_t mpid_MemPool; // memory pool id
  11. osThreadId_t tid_Thread_MemPool; // thread id
  12. void Thread_MemPool (void *argument); // thread function
  13. int Init_MemPool (void) {
  14. mpid_MemPool = osMemoryPoolNew(MEMPOOL_OBJECTS, sizeof(MEM_BLOCK_t), NULL);
  15. if (mpid_MemPool == NULL) {
  16. ; // MemPool object not created, handle failure
  17. }
  18. tid_Thread_MemPool = osThreadNew(Thread_MemPool, NULL, NULL);
  19. if (tid_Thread_MemPool == NULL) {
  20. return(-1);
  21. }
  22. return(0);
  23. }
  24. void Thread_MemPool (void *argument) {
  25. MEM_BLOCK_t *pMem;
  26. osStatus_t status;
  27. while (1) {
  28. ; // Insert thread code here...
  29. pMem = (MEM_BLOCK_t *)osMemoryPoolAlloc(mpid_MemPool, 0U); // get Mem Block
  30. if (pMem != NULL) { // Mem Block was available
  31. pMem->Buf[0] = 0x55U; // do some work...
  32. pMem->Idx = 0U;
  33. status = osMemoryPoolFree(mpid_MemPool, pMem); // free mem block
  34. switch (status) {
  35. case osOK:
  36. break;
  37. case osErrorParameter:
  38. break;
  39. case osErrorNoMemory:
  40. break;
  41. default:
  42. break;
  43. }
  44. }
  45. osThreadYield(); // suspend thread
  46. }
  47. }