仿马老师书中的第十一章测频法测量频率测不准
/*****************************************************Chip type : ATtiny2313V
Clock frequency : 4.000000 MHz
Memory model : Tiny
External SRAM size: 0
Data Stack size : 32
*****************************************************/
#include <tiny2313.h>
#include <stdio.h>
#define uchar unsigned char
bit time_1ms_ok;
unsigned inttime0_old,time0_new;
unsigned int freq;
unsigned char freq_time;
// Timer 0 output compare A interrupt service routine
interrupt void timer0_compa_isr(void) //TO为定时用
{
time0_new=TCNT1;
time_1ms_ok=1;
}
void measure_freq(void);
void main(void)
{
#pragma optsize-
CLKPR=0x80;
CLKPR=0x00;
#ifdef _OPTIMIZE_SIZE_
#pragma optsize+
#endif
// Timer/Counter 0 initialization
// Clock source: System Clock
// Clock value: 62.500 kHz
// Mode: Normal top=FFh
// OC0A output: Disconnected
// OC0B output: Disconnected
TCCR0A=0x02;
TCCR0B=0x01;
TCNT0=0x00;
OCR0A=0x80; //改变此值,可是测得的频率无变化
OCR0B=0x00;
// Timer/Counter 1 initialization
// Clock source: T1 pin Falling Edge
// Mode: Normal top=FFFFh
// OC1A output: Discon.
// OC1B output: Discon.
// Noise Canceler: Off
// Input Capture on Falling Edge
// Timer 1 Overflow Interrupt: Off
// Input Capture Interrupt: Off
// Compare A Match Interrupt: Off
// Compare B Match Interrupt: Off
TCCR1A=0x00;
TCCR1B=0x06;
TCNT1H=0x00;
TCNT1L=0x00;
ICR1H=0x00;
ICR1L=0x00;
OCR1AH=0x00;
OCR1AL=0x00;
OCR1BH=0x00;
OCR1BL=0x00;
GIMSK=0x00;
MCUCR=0x00;
// Timer(s)/Counter(s) Interrupt(s) initialization
TIMSK=0x01;
USICR=0x00;
// USART initialization
// Communication Parameters: 8 Data, 1 Stop, No Parity
// USART Receiver: On
// USART Transmitter: On
// USART Mode: Asynchronous
// USART Baud Rate: 4800
UCSRA=0x00;
UCSRB=0x18;
UCSRC=0x06;
UBRRH=0x00;
UBRRL=0x33;
ACSR=0x80;
#asm("sei")
time0_old=0;
while (1)
{
measure_freq();
};
}
void measure_freq(void)
{
if(time_1ms_ok)
{
if(time0_new>=time0_old)
freq=freq + (time0_new - time0_old);
else
freq=freq + (65536 - time0_old + time0_new);
time0_old=time0_new;
if(++freq_time>=50) //改变此值50,测得的频率无变化
{
freq_time=0;
printf("B%i\n\r",freq);
freq=0;
}
time_1ms_ok=0;
}
} http://cache.amobbs.com/bbs_upload782111/files_16/ourdev_459223.JPG
(原文件名:b.JPG)
上图为在串口中显示的频率值 等待中 是程序问题,经过马老师指点不应用printf,后来改用UDR来发送,已能测出频率。
页:
[1]