1、超声波程序完善了下稳定多了_2007-08-24 06:23#include #include #include #include #include uchar counter=0; float distance;uchar tmp32; uint value,temp; bit ok_flag=0;void timer0_on() if(!ok_flag) TCCR0=0x19;TCNT0=0x00;OCR0=0x0C; void timer0_off()TCCR0=0x00;TCNT0=0x00;OCR0=0x00;/输入捕捉初始化void timer1_on()/ Timer/Count
2、er 1 initialization/ Clock source: System Clock/ Clock value: 1000.000 kHz/ Noise Canceler: On/ Input Capture on Falling Edge/ Timer 1 Overflow Interrupt: Off/ Input Capture Interrupt: OnTCCR1A=0x00;TCCR1B=0x81;TCNT1H=0x00;TCNT1L=0x00;ICR1H=0x00;ICR1L=0x00; void timer1_off()TCCR1A=0x00;TCCR1B=0x00;/
3、 Timer 0 output compare interrupt service routineinterrupt TIM0_COMP void timer0_comp_isr(void)/counter+;/if(counter=2) if(ok_flag=1)timer0_off(); void USART_init()/ USART initialization/ Communication Parameters: 8 Data, 1 Stop, No Parity/ USART Receiver: On/ USART Transmitter: On/ USART Mode: Asyn
4、chronous/ USART Baud rate: 9600 (Double Speed Mode)UCSRA=0x02;UCSRB=0x18;UCSRC=0x86;UBRRH=0x00;UBRRL=0x0C;/ Timer 1 input capture interrupt service routineinterrupt TIM1_CAPT void timer1_capt_isr(void) TCCR1B=0x00;TIMSK=0x02;ok_flag=1;value=ICR1L;temp=ICR1H;TCNT1H=0x00;TCNT1L=0x00; /设置 value值即为 TCNT
5、(new)-TCNT(old)value|=temp8; /ok_flag=1; printf(“here is TIM1_CAPTn“); / Declare your global variables herevoid main(void)PORTB=0x00;DDRB=0x08; PORTD=0xff;/DDRB=0x00;USART_init();/ Timer(s)/Counter(s) Interrupt(s) initializationTIMSK=0x22;/ Global enable interrupts#asm(“sei“)/delay_ms(1000);/timer0_
6、on();/delay_us(800);/timer1_on();while (1) /printf(“here is mainn“);delay_ms(1000);timer0_on(); delay_us(800);timer1_on();if(ok_flag) ok_flag=0; distance=value/1000*0.17;ftoa(distance,2,tmp);puts(tmp);printf(“distance is:n“); delay_ms(1000);TCCR1B=0x81; TIMSK=0x22;/delay_ms(1000);delay_ms(1000);附上原理图:推荐几份比较不错的电路: