求助:AVR 超声波测距的问题,用的srf04,一直显示恒定距离……帮忙看看程序!谢谢了
小弟用的是MEGA128,PB0口是输出Trig,PB1口是输入Echo,麻烦看下,感觉是 计数器 的问题,就是调不出……#include<iom128v.h>
#include<macros.h >
#define uchar unsigned char
#define uint unsigned int
#include"1602.h"
uint get_srf04(void);
uchar wz[]={"Distance is:"};
uchar gd[]={" cm"};
void main(void)
{
uint range,distance,range1,range2,range3;
DDRB = 0xfd; // RB0 (trig) is output
PORTB = 0xfe;
DDRA=0xff;
PORTA=0xff;
DDRG=0xff;
PORTG=0xff;
LcdInit();
WriteChar(2,1,12,wz);
WriteChar(1,1,12,gd);
while(1)
{ // loop forever
range = get_srf04(); // get range from srf04 (round trip flight time in 0.5uS units)
distance=range/116;
range1=distance/100;
range2=(distance-range1*100)/100;
range3=distance-range1*100-range2*10;
range1+=0x30;
range2+=0x30;
range3+=0x30;
WriteNum(1,5,(range1));
WriteNum(1,6,(range2));
WriteNum(1,7,(range3));
TCNT1H=0; // 52mS delay - this is so that the SRF04 ranging is not too rapid
TCNT1L=0;
SREG|=BIT(7); // and the previous pulse has faded away before we start the next one
TCCR1B = 0x02;
TIMSK|=BIT(2); // 1:8 prescale and running
TIFR=0; //置零
while(!TIFR); // wait for delay time
TIMSK&=~BIT(2); // stop timer
}
}
uint get_srf04(void)
{
uchar key;
TCNT1H = 0xff; // 产生10um的开始脉冲prepare timer for 10uS pulse
TCNT1L = 0xEB;
TCCR1B = 0x02;
TIMSK|=BIT(2); // 1:8 prescale and running
TIFR=0; // TOV1
PORTB|=BIT(0); // start trigger pulse
while(!TIFR); // wait 10uS
PORTB&=~BIT(0); // end trigger pulse
TIMSK&=~BIT(2); // stop timer
TCNT1H = 0; // prepare timer to measure echo pulse
TCNT1L = 0;
TCCR1B = 0x02; // 1:8 prescale but not running yet
TIFR=0;
PORTB|=BIT(1);
key=PINB;
key&=0x02; //看返回的高电平长度
while(!key& !TIFR); // wait for echo pulse to start (go high)
TIMSK|=BIT(2); // start timer to measure pulse
while( key& !TIFR); // wait for echo pulse to stop (go low)
TIMSK&=~BIT(2); // stop timer
return (TCNT1H<<8)+TCNT1L; // TMR1H:TMR1L contains flight time of the pulse in 0.8uS units
}
以下是用的 SRF04 资料:
点击此处下载 ourdev_471040.pdf(文件大小:130K) (原文件名:SRF04-tech.pdf) 首先说一下,我对AVR不是很精通,说你的问题之处,如果不对的话请指出来哈:
我觉得:第一;你没有开总中断。
第二:开了总中断的话可能你测的距离已经大于最大时间,while(!key& !TIFR); while( key& !TIFR); 只要中断到了他们都会退出来。所以测的时间可能不对。
第三:我不知道TCNT1H<<8)+TCNT1L;是什么意思,楼主想测时间的话为什么不这样:在中断的时候设一个变量,每一个中断让其加一。到最后就是多少次*中断时间+(65535-计时器里面的值),这样不好吗?
呵呵,本人纯属菜鸟,在此提出问题,还望楼主解答 我也在写,呵呵,望交流 LZ 不知道还在不在 最后问题解决了没有啊 我现在也遇到了相同的问题
页:
[1]