arduino如何在中断函数中编写延时函数


很多用arduino单片机进行电子设计的同学有很多会涉及中断函数的编写,但是对于中断函数中有需要编写延时函数时,常常会有同学碰到很多麻烦。现对中断函数中如何进行延时函数编写做下总结,对大家可能想到的方法做下介绍。

  • for循环

在一般的程序里面我们可以采用三层for循环来实现一般的延时,网上也有针对不同计时器的小软件来帮忙计算i,j,k的值

for(i=0;i<256;i++)
  for(j=o;j<256;j++)
    for(k=0;k<256;k++)

 但是在arduino的中断函数里面对于 空操作有优化,会把空操作快速执行,不能达到延时效果。

  •  delay函数 

delay函数是arduino内的自带的最常用的延时函数,但是它调用avr的timer0,和中断函数冲突,也是无法起作用的。

  • 正解 delayMicroseconds函数
for(int i=0;i<100;i++)
    delayMicroseconds(10000);

 可以使用上述的方法实现在中断函数中的延时,delaymicrosecond()不是使用计时器,而是用avr汇编的loop循环来实现的,所以在中断中,这个函数依然可以起作用。但是注意不要影响下一次的中断的进入,这个函数是微秒级的,最大是16383

Description

Pauses the program for the amount of time (in microseconds) specified as parameter. There are a thousand microseconds in a millisecond, and a million microseconds in a second.

Currently, the largest value that will produce an accurate delay is 16383. This could change in future Arduino releases. For delays longer than a few thousand microseconds, you should use delay() instead.

上述说明是arduino对该函数的描述,供大家参考!

 

发布了11 篇原创文章 · 获赞 11 · 访问量 1万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章