【国民技术N32项目移植】2.天气显示及预报系统之硬件定时器驱动
本篇文章主要介绍了如何在RTT下创建硬件定时器以及使用。
1、查看手册
首先查看RTT官网提供的用户手册:https://www.rt-thread.org/document/site/#/rt-thread-version/rt-thread-standard/programming-manual/device/hwtimer/hwtimer?id=%e5%ae%9a%e6%97%b6%e5%99%a8%e7%ae%80%e4%bb%8b
最后手册中给出了硬件定时器的设备使用例程根据自己使用的具体情况修改即可,流程如下:
- 首先根据定时器设备名称 “timer6” 查找设备获取设备句柄。
- 以读写方式打开设备 “timer6” 。
- 设置定时器超时回调函数,根据自己想要实现的功能编写。
- 设置定时器模式为周期性定时器,并设置超时时间为 1毫秒,此时定时器启动。
2、编写程序
首先在RTT-Settings中打开自己使用的定时器资源,然后开始编写程序。
int hwtimer_sample(void)
{
timer_event = rt_event_create("timer_event",
RT_IPC_FLAG_PRIO);
if (timer_event != RT_NULL)
rt_kprintf("\r\ntimer event create success��\n\n");
rt_err_t ret = RT_EOK;
rt_hwtimerval_t timeout_s;
rt_device_t hw_dev = RT_NULL;
rt_hwtimer_mode_t mode;
hw_dev = rt_device_find(HWTIMER_DEV_NAME);
if (hw_dev == RT_NULL)
{
rt_kprintf("hwtimer sample run failed! can't find %s device!\n", HWTIMER_DEV_NAME);
return RT_ERROR;
}
ret = rt_device_open(hw_dev, RT_DEVICE_OFLAG_RDWR);
if (ret != RT_EOK)
{
rt_kprintf("open %s device failed!\n", HWTIMER_DEV_NAME);
return ret;
}
rt_device_set_rx_indicate(hw_dev, timeout_cb);
mode = HWTIMER_MODE_PERIOD;
ret = rt_device_control(hw_dev, HWTIMER_CTRL_MODE_SET, &mode);
if (ret != RT_EOK)
{
rt_kprintf("set mode failed! ret is :%d\n", ret);
return ret;
}
timeout_s.sec = 0;
timeout_s.usec = 1000;
if (rt_device_write(hw_dev, 0, &timeout_s, sizeof(timeout_s)) != sizeof(timeout_s))
{
rt_kprintf("set timeout value failed\n");
return RT_ERROR;
}
rt_thread_mdelay(3500);
rt_device_read(hw_dev, 0, &timeout_s, sizeof(timeout_s));
rt_kprintf("Read: Sec = %d, Usec = %d\n", timeout_s.sec, timeout_s.usec);
return ret;
}
static rt_err_t timeout_cb(rt_device_t dev, rt_size_t size)
{
static uint16_t timerCount = 1;
if(timerCount % 20 == 0 ){
rt_event_send(timer_event,KEY_EVENT);
}
if(timerCount % 1000 == 0 ){
rt_event_send(timer_event,LCD_EVENT);
ledToggle(LED2_PIN);
}
if(timerCount > 60000){
timerCount = 0;
}
++timerCount;
return 0;
}
3、功能验证
定时器控制LED的闪烁,周期为1S
|