Arduino 中使用定时中断

Arduino 中使用定时中断

分类: 嵌入式   1619人阅读  评论(0)  收藏  举报

Arduino的库中本身没有提供操作定时中断的功能,但是我们以可以avr开发库本身的特性来使用Arduino没有提供的功能.

代码如下, 设置一个1ms的中断, 每隔1s输出一个$符号:

[cpp]  view plain copy
  1. #include <avr/io.h>  
  2. #include <avr/interrupt.h>  
  3.   
  4. /* 
  5.  * 将定时器中断设为1ms 
  6.  */  
  7. void init_time()  
  8. {  
  9.     TCCR2A |= (1 <<WGM21) | (1 << WGM20);  
  10.     TCCR2B |= (1 << CS22 );  //by clk/64  
  11.     TCCR2B &= ~((1 <<CS21) | (1 <<CS20));  //by clk/64  
  12.     TCCR2B &= ~((1 << WGM21 ) | (1 << WGM20));  
  13.     ASSR |= ( 1 << AS2 );  
  14.     TIMSK2 |= ( 1 << TOIE2 ) | ( 0 << OCIE2B );  
  15.     TCNT2 = 6;  
  16.     sei();  
  17. }  
  18.   
  19.   
  20. int count = 0;  
  21. SIGNAL(SIG_OVERFLOW2)  
  22. {  
  23.     TCNT2 = 6;  
  24.       
  25.     ++count;  
  26.     if( count == 1000 )  
  27.     {  
  28.         Serial.print("$ ");  
  29.         count=0;  
  30.     }  
  31. }  
  32.   
  33. /* 
  34. */  
  35. void setup(void)  
  36. {  
  37.     Serial.begin(115200);  
  38.     init_time();  
  39. }  
  40.   
  41. void loop( void )  
  42. {  
  43.     Serial.println("start ... ...");  
  44.   
  45.     while( 1 )  
  46.     {  
  47.         delay( 100 );  
  48.     }  
  49. }  




MsTimer2 is a small and very easy to use library to interface Timer2 with humans. It's called MsTimer2 because it "hardcodes" a resolution of 1 millisecond on timer2.
Updated again:
a new version is available here
UPDATED:
works on ATmega1280 (thanks to Manuel Negri).
works on ATmega328 (thanks Jerome Despatis).
works on ATmega48/88/168 and ATmega128/8.
Methods


MsTimer2::set(unsigned long ms, void (*f)())
this function sets a time on ms for the overflow. Each overflow, "f" will be called. "f" has to be declared void with no parameters.
MsTimer2::start()
enables the interrupt.
MsTimer2::stop()
disables the interrupt.
Source code


License: LGPL
MsTimer2.zip
Install it on {arduino-path}/libraries/
Example


/

// Toggle LED on pin 13 each second
#include <MsTimer2.h>


void flash() {
  static boolean output = HIGH;


  digitalWrite(13, output);
  output = !output;
}


void setup() {
  pinMode(13, OUTPUT);


  MsTimer2::set(500, flash); // 500ms period
  MsTimer2::start();
}


void loop() {
}


Further examples on the Web


Heartbeat effect for Arduino and 20 LEDs
Knight Rider example
Persistence of vision sketch
Power grid monitoring experiment
Bugs


send any bug to javiervalencia80 [at] gmail.com

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值