×
单片机 > 单片机程序设计 > 详情

[AVR应用]Timer1测量正向脉冲的宽度

发布时间:2020-08-21 发布时间:
|
#include

#include

#define ICP PIND.6

sfrw ICR1=0x26; 

flash const unsigned char tabel[]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90};
unsigned char ledbuff[]={0x8c,0x8c,0x8c,0x8c,0x8c,0x8c};

unsigned char ov_counter; //counter for timer1 overflow
unsigned int rising_edge,falling_edge; //storage for times
unsigned long pulse_clocks; //storage for actual clock counts in the pulse

/******************************************************** 
display()
 ********************************************************/
 void display(void)
 {
   unsigned char i;
   for(i=0;i<6;i++)
   {
     PORTC=ledbuff[i];
     PORTD|=(1<      delay_ms(1);
     PORTD&=~(1<    }
 }

/******************************************************** 
count to BCD
 ********************************************************/
 void hextobcd(unsigned long count)
 {
   unsigned char i,temp;
   for(i=0;i<6;i++)
   {
     temp=count%10;
     ledbuff[i]=tabel[temp];
     count=count/10;
   }
 }
   
// Timer 1 output compare A interrupt service routine
interrupt [TIM1_OVF] void timer1_ovf_isr(void)
{
  ov_counter++;
}

interrupt [TIM1_CAPT] void timer1_capt_isr(void)
{
  //check for rising or falling edge by checking the
  //level on ICP. If high,the interrupt must have
  //be triggered by a rising edge and if not, the trigger
  //must have been a falling edge.
  if(ICP)
  {
    rising_edge=ICR1;   //save start time for pulse
    TCCR1B&=~(1<<6);    //set to trigger on falling edge next
    TIFR=(1<<5);
    ov_counter=0;       //clear overflow counter for this measurement
  }
  else
  {
    falling_edge=ICR1;  //save falling edge time
    TCCR1B|=(1<<6);     //set for rising edge trigger next
    TIFR=(1<<5);
    pulse_clocks=(unsigned long)falling_edge-(unsigned long)rising_edge+(unsigned long)ov_counter*65536;
    pulse_clocks=pulse_clocks/500;   //At 2 microseconds per clock tick, it takes 500 clock ticks to 
                                       //make 1 millisecond. Therefore the program divieds the resulting 
                                       //clock ticks by 500 to calculate the correct result in milliseconds.
  }
}

// Declare your global variables here
void main(void)
{
  DDRC=0xFF;                      //set PortC for output
  DDRD=0x3F;
  
  TCCR1B=(1<<7)|(1<<6)|(1<<1);      //Timer1 input to clock/8, enable input
                                  //capture on rising edge and noise canceller
  TIMSK=(1<<5)|(1<<2);  //unmask timer1 overflow and capture interrupts

  #asm("sei")          // Global enable interrupts

  while(1)
  {
    hextobcd(pulse_clocks);
    display();
  }
}

 

『本文转载自网络,版权归原作者所有,如有侵权请联系删除』

热门文章 更多
ARM 汇编的必知必会