Semaphore.c 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. #include "cmsis_os2.h" // CMSIS RTOS header file
  2. /*----------------------------------------------------------------------------
  3. * Semaphore creation & usage
  4. *---------------------------------------------------------------------------*/
  5. osSemaphoreId_t sid_Semaphore; // semaphore id
  6. osThreadId_t tid_Thread_Semaphore; // thread id
  7. void Thread_Semaphore (void *argument); // thread function
  8. int Init_Semaphore (void) {
  9. sid_Semaphore = osSemaphoreNew(2U, 2U, NULL);
  10. if (sid_Semaphore == NULL) {
  11. ; // Semaphore object not created, handle failure
  12. }
  13. tid_Thread_Semaphore = osThreadNew(Thread_Semaphore, NULL, NULL);
  14. if (tid_Thread_Semaphore == NULL) {
  15. return(-1);
  16. }
  17. return(0);
  18. }
  19. void Thread_Semaphore (void *argument) {
  20. int32_t val;
  21. while (1) {
  22. ; // Insert thread code here...
  23. val = osSemaphoreAcquire(sid_Semaphore, 10U); // wait 10 mSec
  24. switch (val) {
  25. case osOK:
  26. ; // Use protected code here...
  27. osSemaphoreRelease(sid_Semaphore); // return a token back to a semaphore
  28. break;
  29. case osErrorResource:
  30. break;
  31. case osErrorParameter:
  32. break;
  33. default:
  34. break;
  35. }
  36. osThreadYield(); // suspend thread
  37. }
  38. }