test_semaphore_isr.c 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. /*
  2. * Copyright (c) 2006-2022, RT-Thread Development Team
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. *
  6. * Change Logs:
  7. * Date Author Notes
  8. * 2018-08-24 yangjie the first version
  9. */
  10. /*
  11. * Demo: semaphore
  12. * This demo creates a periodic hard timer which releases a semaphore when timeout
  13. * A thread blocks on the semaphore
  14. *
  15. */
  16. #include <rtthread.h>
  17. #include <FreeRTOS.h>
  18. #include <semphr.h>
  19. #define THREAD_PRIORITY (FINSH_THREAD_PRIORITY + 1)
  20. #define THREAD_TIMESLICE 5
  21. /* Semaphore handle */
  22. static SemaphoreHandle_t dynamic_sem = RT_NULL;
  23. static rt_timer_t timer1;
  24. #ifdef rt_align
  25. rt_align(RT_ALIGN_SIZE)
  26. #else
  27. ALIGN(RT_ALIGN_SIZE)
  28. #endif
  29. static char thread1_stack[1024];
  30. static struct rt_thread thread1;
  31. static void rt_thread1_entry(void *parameter)
  32. {
  33. static rt_err_t result;
  34. while (1)
  35. {
  36. result = xSemaphoreTake(dynamic_sem, portMAX_DELAY);
  37. if (result != pdPASS)
  38. {
  39. rt_kprintf("thread1 take a dynamic semaphore, failed.\n");
  40. return;
  41. }
  42. else
  43. {
  44. rt_kprintf("thread1 take a dynamic semaphore, succeeded.\n");
  45. }
  46. }
  47. }
  48. static void timeout(void *parameter)
  49. {
  50. rt_kprintf("timer isr give semaphore\n");
  51. xSemaphoreGiveFromISR(dynamic_sem, RT_NULL);
  52. }
  53. int semaphore_isr()
  54. {
  55. /* Create a binary semaphore */
  56. dynamic_sem = xSemaphoreCreateBinary();
  57. if (dynamic_sem == RT_NULL)
  58. {
  59. rt_kprintf("create dynamic semaphore failed.\n");
  60. return -1;
  61. }
  62. rt_thread_init(&thread1,
  63. "thread1",
  64. rt_thread1_entry,
  65. RT_NULL,
  66. &thread1_stack[0],
  67. sizeof(thread1_stack),
  68. THREAD_PRIORITY, THREAD_TIMESLICE);
  69. rt_thread_startup(&thread1);
  70. /* Create a hard timer with period of 5 seconds */
  71. timer1 = rt_timer_create("timer1", timeout, RT_NULL, rt_tick_from_millisecond(5000), RT_TIMER_FLAG_PERIODIC | RT_TIMER_FLAG_HARD_TIMER);
  72. if (timer1 != RT_NULL)
  73. {
  74. rt_timer_start(timer1);
  75. }
  76. return 0;
  77. }
  78. MSH_CMD_EXPORT(semaphore_isr, semaphore sample);