超声波避障程序已经写好了,测试了下,基本还可以,以下是源代码
#include <reg52.h>
#include "header\direction.h"
unsigned char pwm_left_value = 15; //左电机PWM值
unsigned char pwm_right_value = 15; //右电机PWM值
unsigned char angle_value = 12; //舵机角度值,12为居中
unsigned char count_1 = 0; //电机pwm周期计数
unsigned char count_2 = 0; //舵机pwm周期计数
void forward() //前进
{
in_1 = 1;
in_2 = 0;
in_3 = 1;
in_4 = 0;
}
void retreat() //后退
{
in_1 = 0;
in_2 = 1;
in_3 = 0;
in_4 = 1;
}
void turn_left() //左转
{
in_1 = 0;
in_2 = 1;
in_3 = 1;
in_4 = 0;
}
void turn_right() //右转
{
in_1 = 1;
in_2 = 0;
in_3 = 0;
in_4 = 1;
}
void stop() //停止
{
in_1 = 0;
in_2 = 0;
in_3 = 0;
in_4 = 0;
}
void t0_init() //初始化T0定时器,定时0.5ms
{
EA = 1;
ET0 = 1;
TMOD &= 0xf0;
TMOD |= 0x01;
TL0 = 0xa3;
TH0 = 0xff;
TF0 = 0;
TR0 = 1;
}
void in_t0() interrupt 1 //电机调速 + 舵机角度调整
{
TL0 = 0xa3;
TH0 = 0xff;
if(count_1 < pwm_left_value)
pwm_ENA_left = 1;
else
pwm_ENA_left = 0;
if(count_1 < pwm_right_value)
pwm_ENB_right = 1;
else
pwm_ENB_right = 0;
count_1++;
count_1 %= 20; //10ms为一个周期
if(count_2 < angle_value)
pwm_steering_engine = 1;
else
pwm_steering_engine = 0;
count_2++;
count_2 %= 40; //20ms为一个周期
}
下面是超声波模块
#include <reg52.h>
#include "header\chaoshengbo.h"
#include "header\direction.h"
#include "header\delay.h"
unsigned char flag_s; //距离判断
float s; //距离变量
void delay_us(unsigned char x)
{
while(x--);
}
void chaoshengbo_init()
{
csb_trig = 1; //触发脉冲,大于10us
delay_us(10);
csb_trig = 0;
while(!csb_echo); //等待高电平
TR1 = 1; //打开定时器
while(csb_echo); //等待低电平
TR1 = 0; //关闭定时器
s = (TH1 * 256 + TL1) / 58; //距离,单位厘米
if(s >= 25)
flag_s = 1;
else
flag_s = 0;
TH1 = 0;
TL1 = 0;
}
void chaoshengbo()
{
unsigned char left_flag = 1;
unsigned char right_flag = 1;
chaoshengbo_init();
delay(10);
if(flag_s) //如果大于25cm
forward();
if(!flag_s) //如果小于25cm
{
stop(); //停车
angle_value = 9; //转向右边
count_2 = 0;
delay(400);
chaoshengbo_init(); //检测距离
delay(20);
right_flag = flag_s;
angle_value = 12; //居中
count_2 = 0;
delay(400);
angle_value = 16; //转向左边
count_2 = 0;
delay(400);
chaoshengbo_init(); //检测距离
delay(20);
left_flag = flag_s;
angle_value = 12; //居中
count_2 = 0;
delay(400);
flag_s = 1;
}
if(1 == right_flag && 0 == left_flag) //右边的距离大于左边
{
retreat(); //后退
delay(400);
angle_value = 9; //右转
delay(400);
turn_right();
delay(450);
}
if(0 == right_flag && 1 == left_flag) //左边的距离大于右边
{
retreat(); //后退
delay(400);
angle_value = 16; //左转
delay(400);
turn_left();
delay(450);
}
if(0 == right_flag && 0 == left_flag) //两边都不能走
{
retreat(); //后退
delay(800);
}
}
void t1_init() //初始化T1定时器
{
EA = 1;
ET1 = 1;
TMOD &= 0x0f;
TMOD |= 0x10;
TL1 = 0;
TH1 = 0;
TF1 = 0;
//TR1 = 1;
}
void in_t1() interrupt 3
{
csb_echo = 0;
}
下面是主函数
#include <reg52.h>
#include "header\direction.h"
#include "header\chaoshengbo.h"
void main()
{
t0_init();
t1_init();
angle_value = 12;
while(1)
{
chaoshengbo();
}
}