Arduino的库中本身没有提供操作定时中断的功能,但是我们以可以avr开发库本身的特性来使用Arduino没有提供的功能.
代码如下, 设置一个1ms的中断, 每隔1s输出一个$符号:
- #include <avr/io.h>
- #include <avr/interrupt.h>
- /*
- * 将定时器中断设为1ms
- */
- void init_time()
- {
- TCCR2A |= (1 <<WGM21) | (1 << WGM20);
- TCCR2B |= (1 << CS22 ); //by clk/64
- TCCR2B &= ~((1 <<CS21) | (1 <<CS20)); //by clk/64
- TCCR2B &= ~((1 << WGM21 ) | (1 << WGM20));
- ASSR |= ( 1 << AS2 );
- TIMSK2 |= ( 1 << TOIE2 ) | ( 0 << OCIE2B );
- TCNT2 = 6;
- sei();
- }
- int count = 0;
- SIGNAL(SIG_OVERFLOW2)
- {
- TCNT2 = 6;
- ++count;
- if( count == 1000 )
- {
- Serial.print("$ ");
- count=0;
- }
- }
- /*
- */
- void setup(void)
- {
- Serial.begin(115200);
- init_time();
- }
- void loop( void )
- {
- Serial.println("start ... ...");
- while( 1 )
- {
- delay( 100 );
- }
- }
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