scheduler.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2. // 头文件区
  3. //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  4. #include <stdio.h>
  5. #include "scheduler.h"
  6. #include "stm32f30x.h"
  7. static Task_Block_t task_block[TASK_NUM]; // 任务块 根据需求设定任务数量
  8. Task_Ctrl_t Task_Ctrl; // 任务控制块
  9. void SysTick_Handler(void)
  10. {
  11. ISR_CallBlack(&Task_Ctrl); // 每次系统时钟中断,时钟周期加1
  12. }
  13. /**
  14. * @author
  15. * @brief 任务添加函数
  16. * @param 任务执行时间间隔
  17. * @param 任务ID 同时表示任务优先级
  18. * @param 任务主体函数
  19. * @retval NULL
  20. */
  21. void TaskAdd(uint8_t task_id, Task_Handler_t task, uint32_t on_time)
  22. {
  23. if(task_id >= TASK_NUM){
  24. return;
  25. }
  26. task_block[task_id].On_Time = on_time;
  27. task_block[task_id].RunTime = 0;
  28. task_block[task_id].Task_Handler = task;
  29. task_block[task_id].TaskState = 0;
  30. }
  31. /*更新任务状态*/
  32. void UpdateTask(p_Task_Block_t Task_Block)
  33. {
  34. Task_Block->RunTime = 0;
  35. Task_Block->TaskState = 1;
  36. }
  37. /*任务初始化函数*/
  38. void TaskInit(void)
  39. {
  40. Task_Ctrl.Update_State = UpdateTask;
  41. Task_Ctrl.Task = task_block;
  42. SysTick_Config(SystemCoreClock / 1000);
  43. }
  44. /*放在1ms中断中*/
  45. void ISR_CallBlack(p_Task_Ctrl_t Task_Ctrl)
  46. {
  47. if (Task_Ctrl->Task != NULL)
  48. {
  49. for (uint8_t i = 0; i < TASK_NUM; i++)
  50. {
  51. Task_Ctrl->Task[i].RunTime++;
  52. if (Task_Ctrl->Task[i].RunTime > Task_Ctrl->Task[i].On_Time)
  53. {
  54. if(Task_Ctrl->Update_State) {
  55. Task_Ctrl->Update_State(&Task_Ctrl->Task[i]);
  56. }
  57. }
  58. }
  59. }
  60. }
  61. void TaskStart()
  62. {
  63. static uint8_t i = 0;
  64. while (1)
  65. {
  66. for (i = 0; i < TASK_NUM; i++)
  67. {
  68. if (Task_Ctrl.Task[i].TaskState)
  69. {
  70. Task_Ctrl.Task[i].TaskState = 0;
  71. if(Task_Ctrl.Task[i].Task_Handler) {
  72. Task_Ctrl.Task[i].Task_Handler();
  73. }
  74. }
  75. }
  76. }
  77. }