|
本帖最后由 anan111 于 2019-6-19 16:58 编辑
这是我自己做的超声波避障小车。
1.51单片机
2.L298N驱动板
3.电机2
4.差速轮2,万向轮1
enA,enB可不接
#include<reg52.h>
//定义L298N端口
sbit in1 = P0^0;
sbit in2 = P0^1;
sbit in3 = P0^2;
sbit in4 = P0^3;
sbit enA = P0^4;
sbit enB = P0^5;
//定义超声波模块端口
sbit Trig = P1^2;
sbit Echo = P1^3;
unsigned int distance_cm = 0; //距离
unsigned int overflow_count = 0; //溢出计数
unsigned int status = 0; //超声波模块状态
unsigned int dis_count = 0; //计数
unsigned char tmp, dat, flat;
unsigned int num, model, c=0;
unsigned int speed = 100;
void chaoshengbo_init(void);
void GetDistance(void);
void delay(unsigned int z)
{
unsigned int x, y;
for(x = z; x > 0 ; x--)
for(y=110;y>0;y--)
;
}
void delay_us(unsigned int aa)
{
while(aa--);
}
//小车右转
void right(unsigned char pwm)
{
enA = 1;
in1 = 0;
in2 = 1;
in3 = 0;
in4 = 0;
delay_us( pwm );
enA = 1;
in1 = 0;
in2 = 0;
in3 = 0;
in4 = 0;
delay_us( 100 - pwm );
}
void r(void)
{
enA = 1;
in1 = 0;
in2 = 1;
in3 = 0;
in4 = 0;
}
//小车左转
void left(unsigned char pwm)
{
enA = 1;
in1 = 0;
in2 = 0;
in3 = 1;
in4 = 0;
delay_us( pwm );
enA = 1;
in1 = 0;
in2 = 0;
in3 = 0;
in4 = 0;
delay_us( 100 - pwm );
}
void l(void)
{
enA = 1;
in1 = 0;
in2 = 0;
in3 = 1;
in4 = 0;
}
//小车后退
void back(unsigned char pwm)
{
enA = 1;
enB = 1;
in1 = 1;
in2 = 0;
in3 = 1;
in4 = 0;
delay_us( pwm );
enA = 1;
in1 = 0;
in2 = 0;
in3 = 0;
in4 = 0;
delay_us( 100 - pwm );
}
void b(void)
{
enA = 1;
enB = 1;
in1 = 1;
in2 = 0;
in3 = 1;
in4 = 0;
}
//小车前进
void forward(unsigned char pwm)
{
enA = 1;
enB = 1;
in1 = 0;
in2 = 1;
in3 = 0;
in4 = 1;
delay_us( pwm );
enA = 1;
in1 = 0;
in2 = 0;
in3 = 0;
in4 = 0;
delay_us( 100 - pwm );
}
void f(void)
{
enA = 1;
enB = 1;
in1 = 0;
in2 = 1;
in3 = 0;
in4 = 1;
}
//小车停止
void stop(void)
{
enB = 1;
in1 = 0;
in2 = 0;
in3 = 0;
in4 = 0;
}
void main(void)
{
chaoshengbo_init();
while(1)
{
b();
GetDistance();
if(distance_cm > 0 && distance_cm <= 15)
{
f();
delay(1000);
r();
delay(1000);
}
}
}
//超声波模块初始化
void chaoshengbo_init(void)
{
Trig = 0;
//TH2 = RCAP2H = 0;
//TL2 = RCAP2L = 0;
TH0 = TL0 = 0;
TR0 = 0; //关闭定时器2
ET0 = 1; //允许T2中断
}
//超声波模块获取距离
void GetDistance(void)
{
Trig = 1; //发送触发信号
status = 1; //status状态默认位1
TH0 = 0;
TL0 = 0;
TR0 = 1; //打开定时器2
while(TL0 < 42) //产生超过10us的脉冲
;
status = 2; //状态设为2
Trig = 0;
TR0 = 0;
TH0 = 0;
TL0 = 0;
overflow_count = 0;
TR0 = 1; //打开定时器2
while(Echo == 0) //当无信号返回时
{
if(status == 5)
{
status = 0;
distance_cm = 0;
break ; //失败
}
}
TR0 = 0; //清空计数
TH0 = 0;
TL0 = 0;
overflow_count = 0;
TR0 = 1;
while(Echo == 1) //有信号返回时,开始计算长度
{
if(status == 5) //status为5时失败
{
status = 0;
distance_cm = 0;
TR0 = 0;
break ;
}
}
dis_count = overflow_count * 65536 + TH0 * 256 + TL0;
TR0 = 0;
distance_cm = (unsigned int)( (long)(dis_count) * 34 / 10000);
status = 0 ; //准备下次发送
}
//定时器2中断
void Timer0Int() interrupt 1
{
TF0 = 0;
overflow_count++;
TH0 = 0;
TL0 = 0;
if(overflow_count == 2)
{
status = 5; //超时
}
}
|
|