本文引用自
https://www.arduino.cn/thread-12445-1-1.html
// 控制 LED 亮滅, 每秒閃爍 5 次: 亮 0.1 秒滅 0.1 秒 ...// Prescaler 用 64volatile int ggyy = 1; // 使用這當 Flag 給 ISR 使用 !int ledPin =13;/// For Prescaler == 64/// 1 秒 / (16 000 000 / 64) = 1/250000 = 0.000004 sec / per cycle/// 0.1 sec / 0.000004 sec -1 = 25000 -1 = 24999const int myTOP = 24999; // 0.1 sec when Prescaler == 64///// Interrupt Service Routine for TIMER1 CTC on OCR1A as TOP/// 注意以下名稱是有意義的, 不可亂改 !ISR(TIMER1_COMPA_vect){ digitalWrite(ledPin, ggyy); // ggyy 是 0 或 1 ggyy = 1 - ggyy; // 給下次進入 ISR 用}void setup( ) { pinMode(ledPin, OUTPUT); digitalWrite(ledPin, LOW); // turn Off the LED cli(); // 禁止中斷 TCCR1A = 0; TCCR1B = 0; TCCR1B |= (1<<WGM12); // CTC mode; Clear Timer on Compare /// CS12, CS11, and CS10 這三個 bit 都是 1 表示使用 External clock // ? TCCR1B |= (1<<CS11); // External clock ??? // ? External clock source on T1 pin. Clock on rising edge ? // CS12 與 CS10 都是 1 表示 Prescaler 為 1024 // See [url=http://www.engblaze.com/microcontroller-tutorial-avr-and-arduino-timer-interrupts/#config]http://www.engblaze.com/microcon ... -interrupts/#config[/url] // TCCR1B |= (1<<CS10) | (1<<CS12); // Prescaler == 1024 TCCR1B |= (1<<CS10) | (1<<CS11); // Prescaler == 64 ///////// OCR1A = myTOP; // TOP count for CTC, 與 prescaler 有關 TCNT1=0; // counter 歸零 TIMSK1 |= (1 << OCIE1A); // enable CTC for TIMER1_COMPA_vect sei(); // 允許中斷}void loop() { //... 做其他事 // if( ggyy == 1) ...}////////