久一网络科技

久一网络科技是您快速建站的首选,我们提供快速高效的服务:快速建站,服务器运维,整站建设,网络编程,网络安全等。持久的品质保证,始终如一的服务理念,久一网络科技-----您身边的网络专家。 如有需求,请联系:tech@jooyee.net

传感器用的是这个网址的超声波一体化发射接收器:

http://www.parallax.com/tabid/768/txtSearch/ultrasonic/List/0/SortField/4/Default.aspx

虽然只有三个脚,但是功能很强大的。

这是通讯协议:


下面是程序,很诡异的代码,参考它给出的basic示例代码写的,果然有效,有点值得注意的是avr的延时函数真的得好好注意,还有NOP()不一定就是1us:


//包含所需头文件
#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>

/*------宏定义------*/
#define uchar unsigned char
#define uint unsigned int
#define BIT(x) (1<<(x))
#define NOP() asm("nop")
#define WDR() asm("wdr")



//端口初始化
void port_init(void)
{
PORTA = 0x00;
DDRA = 0x01;
PORTB = 0x00;
DDRB = 0x01;
PORTC = 0x00;
DDRC = 0x00;
PORTD = 0x00;
DDRD = 0x00;
}



void init_devices(void)
{
cli(); //禁止所有中断
MCUCR = 0x00;
MCUCSR = 0x80;//禁止JTAG
GICR = 0x00;
port_init();
sei();//开全局中断
}



//主函数,NOP();并不准确,要用winavr内部自带的才准确
int main(void)
{
init_devices();

long i=0,j=0,k=0;
int distance=0;

for(k=0 ;k< 150 ;k++) _delay_ms(10) ;
for(;;)
{
i=0;
j=0;
distance=0;

DDRB |= BIT(PB0);//output
PORTB &= ~BIT(PB0);
_delay_us(45);
PORTB |= BIT(PB0);
_delay_us(5);
PORTB &= ~BIT(PB0);//>2us pulse
_delay_us(545);
DDRB &= ~BIT(PB0);//input

while(!(PINB & BIT(PB0))) //Wait For Pin To Go HIGH
{
i++;
_delay_us(1);
}
while((PINB & BIT(PB0))) //Wait For Pin To Go LOW
{
j++;
_delay_us(1);
}

distance=332 * (j-i)/1000/2;//ms
if(distance<=100) //30cm
{
PORTA ^= BIT(PA0);
}

for(k=0 ;k< 100 ;k++) _delay_ms(10) ;

}
return 0;
}

0 评论 ---->點閱數:

发表评论

关注者

热门帖子

网页浏览总次数