收藏官网首页
查看: 15313|回复: 5

【一起来玩RTOS系列】之RT-Thread 软件定时器-动态方法

321

主题

1054

帖子

4502

积分

论坛元老

Rank: 8Rank: 8

积分
4502
QQ
跳转到指定楼层
楼主
发表于 2017-11-18 21:24:16 | 只看该作者 |只看大图 回帖奖励 |倒序浏览 |阅读模式
注册成为机智云开发者,手机加虚拟设备快速开发
定时器,是指从指定的时刻开始,经过一个指定时间,然后触发一个事件,类似定个时间提醒第二天能够按时起床。定时器有硬件定时器和软件定时器之分:
硬件定时器是芯片本身提供的定时功能。一般是由外部晶振提供给芯片输入时钟,芯片向软件模块提供一组配置寄存器,接受控制输入,到达设定时间值后芯片中断控制器产生时钟中断。硬件定时器的精度一般很高,可以达到纳秒级别,并且是中断触发方式。
软件定时器是由操作系统提供的一类系统接口(函数),它构建在硬件定时器基础之上,使系统能够提供不受数目限制的定时器服务。
在操作系统中,通常软件定时器以系统节拍(tick)为单位。节拍长度指的是周期性硬件定时器两次中断间的间隔时间长度。这个周期性硬件定时器也称之为操作系统时钟。软件定时器以这个节拍时间长度为单位,数值必须是这个节拍的整数倍,例如节拍是10ms,那么上层软件定时器只能是10ms,20ms,100ms等,而不能取值为15ms。由于节拍定义了系统中定时器能够分辨的精确度,系统可以根据实际系统CPU的处理能力和实时性需求设置合适的数值,tick值设置越小,精度越高,但是系统开销也将越大(在1秒中系统用于处理时钟中断的次数 也就越多)。RT-Thread的定时器也基于类似的系统节拍,提供了基于节拍整数倍的定时能力。
RT-Thread的定时器提供两类定时器机制:第一类是单次触发定时器,这类定时器在启动后只会触发一次定时器事件,然后定时器自动停止。第二类是周期触发定时器,这类定时器会周期性的触发定时器事件,直到用户手动的停止定时器否则将永远持续执行下去。

使用动态API创建定时器示例如下:


  1. /**
  2.   ****************************************************
  3.   * File Name          : main.c
  4.   * Description        : Main program body
  5.   ****************************************************
  6.   ** This notice applies to any and all portions of this file
  7.   * that are not between comment pairs USER CODE BEGIN and
  8.   * USER CODE END. Other portions of this file, whether
  9.   * inserted by the user or by software development tools
  10.   * are owned by their respective copyright owners.
  11.   *
  12.   * COPYRIGHT(c) 2017 STMicroelectronics
  13.   *
  14.   * Redistribution and use in source and binary forms, with or without modification,
  15.   * are permitted provided that the following conditions are met:
  16.   *   1. Redistributions of source code must retain the above copyright notice,
  17.   *      this list of conditions and the following disclaimer.
  18.   *   2. Redistributions in binary form must reproduce the above copyright notice,
  19.   *      this list of conditions and the following disclaimer in the documentation
  20.   *      and/or other materials provided with the distribution.
  21.   *   3. Neither the name of STMicroelectronics nor the names of its contributors
  22.   *      may be used to endorse or promote products derived from this software
  23.   *      without specific prior written permission.
  24.   *
  25.   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  26.   * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  27.   * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  28.   * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  29.   * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  30.   * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  31.   * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  32.   * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  33.   * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  34.   * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  35.   *
  36.   ****************************************************
  37.   */
  38. /* Includes ------------------------------------------------------------------*/
  39. #include "main.h"
  40. #include "STM32f1xx_hal.h"
  41. #include "usart.h"
  42. #include "gpio.h"

  43. /* USER CODE BEGIN Includes */
  44. #include "rtthread.h"
  45. /* USER CODE END Includes */

  46. /* Private variables ---------------------------------------------------------*/

  47. /* USER CODE BEGIN PV */
  48. /* Private variables ---------------------------------------------------------*/

  49. /* USER CODE END PV */

  50. /* Private function prototypes -----------------------------------------------*/
  51. void SystemClock_Config(void);

  52. /* USER CODE BEGIN PFP */
  53. /* Private function prototypes -----------------------------------------------*/

  54. /* USER CODE END PFP */

  55. /* USER CODE BEGIN 0 */
  56. //重映射串口1到rt_kprintf
  57. void rt_hw_console_output(const char *str)
  58. {
  59.     /* empty console output */
  60.         char aa='\r';
  61.           rt_enter_critical();

  62.                 while(*str!='\0')
  63.                 {
  64.                         if(*str=='\n')
  65.                         {
  66.                                 HAL_UART_Transmit(&huart1, (uint8_t *)&aa, 1, 10);
  67.                         }
  68.                                 HAL_UART_Transmit(&huart1, (uint8_t *)(str++), 1, 10);
  69.                 }
  70.                
  71.                 rt_exit_critical();
  72. }
  73. //线程LED1
  74. static void led1_thread_entry(void* parameter)
  75. {
  76.        while(1)
  77.        {
  78.              LED1_Toggle();
  79.              rt_thread_delay(500);   //延时
  80.                                                  rt_kprintf("this is thread 1\r\n");
  81.        }
  82. }
  83. //线程LED2
  84. static void led2_thread_entry(void* parameter)
  85. {
  86.        while(1)
  87.        {
  88.              LED2_Toggle();
  89.              rt_thread_delay(100);   //延时
  90.                                                  rt_kprintf("this is thread 2\r\n");
  91.        }
  92. }

  93. /* 定时器的控制块 */
  94. static rt_timer_t timer1;
  95. static rt_timer_t timer2;

  96. /* 定时器1超时函数 */
  97. static void timeout1(void* parameter)
  98. {
  99.     rt_kprintf("periodic timer is timeout\n");
  100.                 LED3_Toggle();
  101. }

  102. /* 定时器2超时函数 */
  103. static void timeout2(void* parameter)
  104. {
  105.     rt_kprintf("one shot timer is timeout\n");
  106.          LED4_Toggle();
  107. }

  108. /* USER CODE END 0 */

  109. int main(void)
  110. {

  111.   /* USER CODE BEGIN 1 */

  112.   /* USER CODE END 1 */

  113.   /* MCU Configuration----------------------------------------------------------*/

  114. //  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  115. //  HAL_Init();

  116. //  /* USER CODE BEGIN Init */

  117. //  /* USER CODE END Init */

  118. //  /* Configure the system clock */
  119. //  SystemClock_Config();

  120. //  /* USER CODE BEGIN SysInit */

  121. //  /* USER CODE END SysInit */

  122. //  /* Initialize all configured peripherals */
  123. //  MX_GPIO_Init();
  124. //  MX_USART1_UART_Init();

  125.   /* USER CODE BEGIN 2 */
  126.        
  127.         rt_thread_t tid1=RT_NULL;//线程句柄
  128.         rt_thread_t tid2=RT_NULL;//线程句柄
  129.        
  130.         //创建动态线程
  131.         tid1=rt_thread_create("led1",//线程名字
  132.                              led1_thread_entry,//线程入口函数
  133.                              RT_NULL,//线程参数
  134.                              256,//线程栈大小
  135.                              3,//线程优先级
  136.                              20);//线程时间片
  137.         //启动线程       
  138.         rt_thread_startup(tid1);

  139.         //创建动态线程
  140.         tid2=rt_thread_create("led2",//线程名字
  141.                              led2_thread_entry,//线程入口函数
  142.                              RT_NULL,//线程参数
  143.                              256,//线程栈大小
  144.                              4,//线程优先级
  145.                              20);//线程时间片
  146.         //启动线程                                                                                                         
  147.         rt_thread_startup(tid2);
  148.        
  149.                 /* 创建定时器1 */
  150.         timer1 = rt_timer_create("timer1",  /* 定时器名字是 timer1 */
  151.                                                                                         timeout1, /* 超时时回调的处理函数 */
  152.                                                                                         RT_NULL,  /* 超时函数的入口参数 */
  153.                                                                                         1000,       /* 定时长度,以OS Tick为单位,即1000个OS Tick */
  154.                                                                                         RT_TIMER_FLAG_PERIODIC); /* 周期性定时器 */
  155.         /* 启动定时器 */
  156.         if (timer1 != RT_NULL) rt_timer_start(timer1);

  157.         /* 创建定时器2 */
  158.         timer2 = rt_timer_create("timer2",   /* 定时器名字是 timer2 */
  159.                                                                                         timeout2, /* 超时时回调的处理函数 */
  160.                                                                                         RT_NULL,  /* 超时函数的入口参数 */
  161.                                                                                         5000,       /* 定时长度为5000个OS Tick */
  162.                                                                                         RT_TIMER_FLAG_ONE_SHOT); /* 单次定时器 */

  163.         /* 启动定时器 */
  164.         if (timer2 != RT_NULL) rt_timer_start(timer2);


  165.   /* USER CODE END 2 */

  166.   /* Infinite loop */
  167.   /* USER CODE BEGIN WHILE */
  168. //  while (1)
  169. //  {
  170.   /* USER CODE END WHILE */

  171.   /* USER CODE BEGIN 3 */
  172. //               
  173. //  }
  174.   /* USER CODE END 3 */

  175. }

  176. /** System Clock Configuration
  177. */
  178. void SystemClock_Config(void)
  179. {

  180.   RCC_OscInitTypeDef RCC_OscInitStruct;
  181.   RCC_ClkInitTypeDef RCC_ClkInitStruct;

  182.     /**Initializes the CPU, AHB and APB busses clocks
  183.     */
  184.   RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE;
  185.   RCC_OscInitStruct.HSEState = RCC_HSE_ON;
  186.   RCC_OscInitStruct.HSEPredivValue = RCC_HSE_PREDIV_DIV1;
  187.   RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  188.   RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  189.   RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSE;
  190.   RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL9;
  191.   if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  192.   {
  193.     _Error_Handler(__FILE__, __LINE__);
  194.   }

  195.     /**Initializes the CPU, AHB and APB busses clocks
  196.     */
  197.   RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
  198.                               |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  199.   RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  200.   RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  201.   RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
  202.   RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  203.   if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
  204.   {
  205.     _Error_Handler(__FILE__, __LINE__);
  206.   }

  207.     /**Configure the Systick interrupt time
  208.     */
  209.   HAL_SYSTICK_Config(HAL_RCC_GetHCLKFreq()/1000);

  210.     /**Configure the Systick
  211.     */
  212.   HAL_SYSTICK_CLKSourceConfig(SYSTICK_CLKSOURCE_HCLK);

  213.   /* SysTick_IRQn interrupt configuration */
  214.   HAL_NVIC_SetPriority(SysTick_IRQn, 0, 0);
  215. }

  216. /* USER CODE BEGIN 4 */

  217. /* USER CODE END 4 */

  218. /**
  219.   * @brief  This function is executed in case of error occurrence.
  220.   * @param  None
  221.   * @retval None
  222.   */
  223. void _Error_Handler(char * file, int line)
  224. {
  225.   /* USER CODE BEGIN Error_Handler_Debug */
  226.   /* User can add his own implementation to report the HAL error return state */
  227.   while(1)
  228.   {
  229.   }
  230.   /* USER CODE END Error_Handler_Debug */
  231. }

  232. #ifdef USE_FULL_ASSERT

  233. /**
  234.    * @brief Reports the name of the source file and the source line number
  235.    * where the assert_param error has occurred.
  236.    * @param file: pointer to the source file name
  237.    * @param line: assert_param error line source number
  238.    * @retval None
  239.    */
  240. void assert_failed(uint8_t* file, uint32_t line)
  241. {
  242.   /* USER CODE BEGIN 6 */
  243.   /* User can add his own implementation to report the file name and line number,
  244.     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  245.   /* USER CODE END 6 */

  246. }

  247. #endif

  248. /**
  249.   * @}
  250.   */

  251. /**
  252.   * @}
  253. */

  254. /**************** (C) COPYRIGHT STMicroelectronics ****END OF FILE***/
复制代码

打开串口助手可以看到如下日志:


实验结果和预期一致:


源码下载:
Gokit_RT-Thread.zip (8.64 MB, 下载次数: 15)

1、机智云QQ群:G1群:104975951 G2群:491509598 G3群:287087942
机智云爱好者-APP开发群: 599735135
QQ群目前非常活跃,欢迎大家参与进来,交流,讨论,答疑,解惑~~
2、机智云微信公众号: 机智云 gizwits、 机智云智能宠物屋go-iot
关注机智云Gizwits官方公众号随时掌握最新资讯和活动信息

1

主题

6

帖子

214

积分

中级会员

Rank: 3Rank: 3

积分
214
沙发
发表于 2017-11-19 16:34:53 | 只看该作者
请问做一个较长时间(几小时-几天)的定时功能也可以用这个方法吗?大神有空的话可以看下我发的提问帖,多谢!

点评

时间较长建议用RTC;你使用一个变量,加定时器也是可以的,32位变量,1ms时基可以定时最长约50天  详情 回复 发表于 2017-11-22 09:27

321

主题

1054

帖子

4502

积分

论坛元老

Rank: 8Rank: 8

积分
4502
QQ
板凳
 楼主| 发表于 2017-11-22 09:27:18 | 只看该作者
Garfieldang 发表于 2017-11-19 16:34
请问做一个较长时间(几小时-几天)的定时功能也可以用这个方法吗?大神有空的话可以看下我发的提问帖,多 ...

时间较长建议用RTC;你使用一个变量,加定时器也是可以的,32位变量,1ms时基可以定时最长约50天
1、机智云QQ群:G1群:104975951 G2群:491509598 G3群:287087942
机智云爱好者-APP开发群: 599735135
QQ群目前非常活跃,欢迎大家参与进来,交流,讨论,答疑,解惑~~
2、机智云微信公众号: 机智云 gizwits、 机智云智能宠物屋go-iot
关注机智云Gizwits官方公众号随时掌握最新资讯和活动信息

0

主题

15

帖子

53

积分

注册会员

Rank: 2

积分
53
地板
发表于 2017-11-22 11:33:39 | 只看该作者
厉害了                                 

10

主题

112

帖子

1545

积分

金牌会员

Rank: 6Rank: 6

积分
1545
5#
发表于 2018-1-28 20:36:55 来自手机 | 只看该作者
汉枫LPB120模块
定时插座是用这个方法实现的吗?

点评

不是  详情 回复 发表于 2018-1-28 21:48

321

主题

1054

帖子

4502

积分

论坛元老

Rank: 8Rank: 8

积分
4502
QQ
6#
 楼主| 发表于 2018-1-28 21:48:34 | 只看该作者
maomaodemao 发表于 2018-1-28 20:36
定时插座是用这个方法实现的吗?

不是
1、机智云QQ群:G1群:104975951 G2群:491509598 G3群:287087942
机智云爱好者-APP开发群: 599735135
QQ群目前非常活跃,欢迎大家参与进来,交流,讨论,答疑,解惑~~
2、机智云微信公众号: 机智云 gizwits、 机智云智能宠物屋go-iot
关注机智云Gizwits官方公众号随时掌握最新资讯和活动信息
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

加入Q群 返回顶部

版权与免责声明 © 2006-2024 Gizwits IoT Technology Co., Ltd. ( 粤ICP备11090211号 )

快速回复 返回顶部 返回列表