Contents ...
udn網路城邦
arduino led閃爍 使用timer延遲5秒
2025/01/06 13:11
瀏覽57
迴響0
推薦0
引用0
#include<avr/io.h>

#include<avr/interrupt.h>

#define F_CPU 16000000UL

volatile unsigned int overflow_count = 0;


void timer1_normal_setup(){

   // set TIMER1 as Normal Mode

   // WGM[13:10] = 0

   TCCR1A &= ~(1<<WGM11)|~(1<<WGM10);

   TCCR1B &= ~(1<<WGM13)|~(1<<WGM12);

   

   // set prescaler as No prescaling

   // CS12=0, CS11=0, CS10=1

   TCCR1B &= ~(1<<CS12)|~(1<<CS11);

   TCCR1B |= (1<<CS10);


   TCNT1 = 0;             // count from 0

   TIMSK1 |= (1<<TOIE1);  // enable TIMER1 overflow interrupt

   sei();                 // enable global interrupt

}


void pin_setup(){

  DDRB |= (1<<PB2);      // set PORTB2 as output

  PORTB &= ~(1<<PB2);    // set PORTB2 as LOW

}


ISR(TIMER1_OVF_vect){

  overflow_count ++;

  

  if(overflow_count == 1220){// 4096us*1220=4.997120秒 延遲5秒

    PORTB ^= (1<<PB2);     // toggle PORTB2

    overflow_count = 0;

  }

}

int main(){

  timer1_normal_setup();

  pin_setup();

  while(1){};

}

限會員,要發表迴響,請先登入