chiaming 发表于 2009-9-4 16:51:03

马老师你好:为何mega128中ICP捕捉占空比(PWM)读取到的值跟波形一直乱跳???

为了计算"加速度计"的值而抓取它的信号, 希望能有稳定准确的占空比!
但找了很多数据, 都查不出问题所在...
麻烦请教,谢谢!!

系统clk: 1M Hz , 预分频: clk/8 ,

code:

#include <avr/io.h>
#include <avr/iom128.h>
#include <avr/interrupt.h>
#include "RS-232.h"

#definefOSC 1000000 // System clock
#defineBUAD 4800 // buad rate : 4800
#defineUBRR fOSC/16/BUAD-1

unsigned int temp_rising = 0;
unsigned int temp_falling = 0;
unsigned int temp_l = 0;
unsigned int temp_h = 0;
unsigned int pwm = 0;

ISR(TIMER1_CAPT_vect)
{
switch(TCCR1B)
{
case 0x82:
temp_l = ICR1L;
temp_h = ICR1H;
temp_rising = ICR1;

TCCR1B = TCCR1B & 0xBF; //TCCR1B = 0x82, 改为下降缘触发
TIFR = 0x20;
break;

case 0xC2:
temp_l = ICR1L;
temp_h = ICR1H;
temp_falling = ICR1;

TCCR1B = TCCR1B | 0x40; //TCCR1B = 0xC2, 改为上升缘触发
TIFR = 0x20;
break;
}

pwm = temp_falling - temp_rising;

USART_Transmit(pwm);
}

int main(void)
{
DDRD = 0x00;

TCCR1B = (1 << ICNC1)|(1 << ICES1)|(1 << CS11);      //初始为上升缘触发
TIMSK = (1 << TICIE1);
TIFR = (1 << ICF1);

USART_Init(UBRR);

sei();

while(1)
{
}
}

void USART_Init(unsigned int ubrr1)
{
// Set baud rate //
UBRR1H = (unsigned char)ubrr1 >> 8;
UBRR1L = (unsigned char)ubrr1;

UCSR1B = (1 << RXEN1)|(1 << TXEN1); // Enable receiver, transmitter //

UCSR1C = (1 << UCSZ11)|(1 << UCSZ10); // Set frame format: 8 data, 1 stop bit //
}

void USART_Transmit(unsigned int data)
{
while(!(UCSR1A & (1 << UDRE1))); // Wait for empty transmit buffer //

UDR1 = data; // Put data into buffer, sends the data //
}

skyward 发表于 2009-10-21 22:43:00

我刚看了一篇帖子说在捕获中断里改触发方式无效,不知道真的假的,参考http://www.ourdev.cn/bbs/bbs_content.jsp?bbs_sn=3311500&bbs_page_no=1&search_mode=4&search_text=skyward&bbs_id=9999
页: [1]
查看完整版本: 马老师你好:为何mega128中ICP捕捉占空比(PWM)读取到的值跟波形一直乱跳???