Semaphore.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. #include "cmsis_os.h" // CMSIS RTOS header file
  2. /*----------------------------------------------------------------------------
  3. * Semaphore creation & usage
  4. *---------------------------------------------------------------------------*/
  5. void Thread_Semaphore (void const *argument); // thread function
  6. osThreadId tid_Thread_Semaphore; // thread id
  7. osThreadDef (Thread_Semaphore, osPriorityNormal, 1, 0); // thread object
  8. osSemaphoreId sid_Thread_Semaphore; // semaphore id
  9. osSemaphoreDef (SampleSemaphore); // semaphore object
  10. int Init_Semaphore (void) {
  11. sid_Thread_Semaphore = osSemaphoreCreate (osSemaphore(SampleSemaphore), 1);
  12. if (!sid_Thread_Semaphore) {
  13. ; // Semaphore object not created, handle failure
  14. }
  15. tid_Thread_Semaphore = osThreadCreate (osThread(Thread_Semaphore), NULL);
  16. if (!tid_Thread_Semaphore) return(-1);
  17. return(0);
  18. }
  19. void Thread_Semaphore (void const *argument) {
  20. int32_t val;
  21. while (1) {
  22. ; // Insert thread code here...
  23. val = osSemaphoreWait (sid_Thread_Semaphore, 10); // wait 10 mSec
  24. switch (val) {
  25. case osOK:
  26. ; // Use protected code here...
  27. osSemaphoreRelease (sid_Thread_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. }