单片机笔记---测量计算输入的脉冲宽度

  使能输入捕捉功能, 测量计算输入的脉冲宽度:

//ICC-AVR application builder : 2006-7-14 10:13:46
// Target : M128
// Crystal: 14.7456Mhz

#include <iom128v.h>
#include <macros.h>

//define PORT B as output for pulse width
#define pulse_out PORTB

//define ICP so we can read the pin
#define ICP PIND4

unsigned char ov_counter;
unsigned int  rising_edge, falling_edge;
unsigned long pulse_clocks;

void port_init(void)
{
 PORTA = 0x00;
 DDRA  = 0x00;
 PORTB = 0xFF;
 DDRB  = 0xFF;
 PORTC = 0x00; //m103 output only
 DDRC  = 0x00;
 PORTE = 0x00;
 DDRE  = 0x00;
 PORTF = 0x00;
 DDRF  = 0x00;
 PORTG = 0x00;
 DDRG  = 0x00;
}

//TIMER0 initialize - prescale:1024
// WGM: Normal
// desired value: 14.44444444KHz
// actual value: -0.001KHz (1444544.4%)
void timer1_init(void)
{
 TCCR1B = 0xc4; //start timer 预分频为64
}

#pragma interrupt_handler timer1_ovf_isr:15
void timer1_ovf_isr(void)
{
  ov_counter++;
}

#pragma interrupt_handler timer1_capt_isr:13
void timer1_capt_isr(void)
{
if (ICP)
{
  rising_edge=ICR1;  //save start time for pulse
  TCCR1B&=0xBF; //set to trigger on falling edge next
  ov_counter=0;
}

else
{
  falling_edge =ICR1;
  TCCR1B|=0x40; 
  pulse_clocks= (unsigned long) falling_edge - (unsigned long) rising_edge
                +(unsigned long) ov_counter*0x10000;
  pulse_out=pulse_clocks/230;
}
}
  

//call this routine to initialise all peripherals
void init_devices(void)
{
 //stop errant interrupts until set up
 CLI(); //disable all interrupts
 XDIV  = 0x00; //xtal divider
 XMCRA = 0x00; //external memory
 port_init();

 MCUCR = 0x00;
 EICRA = 0x00; //extended ext ints
 EICRB = 0x00; //extended ext ints
 EIMSK = 0x00;
 TIMSK = 0x00; //timer interrupt sources
 ETIMSK = 0x00; //extended timer interrupt sources
 SEI(); //re-enable interrupts
 //all peripherals are now initialised
}

void main(void)

  port_init();
  init_devices();
  timer1_init();
  TIMSK=0x24;
  SEI();
  while(1)
  {
   ;
  }
}  

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值