一、L298驱动电机接线图
二、左、中、右循迹模块接线图及左、右避障模块接线图
三、主函数
/************三路S弯循迹**************/
#include <reg52.h>
#include "Motor.h"
sbit ENA = P1^6;//左两轮使能
sbit ENB = P1^7;//右两轮使能,LN298引脚定义
sbit Left_Trace = P3^7;//左循迹
sbit Right_Trace = P3^6;//右循迹
sbit Mid_Trace = P0^0;//中循迹
unsigned char time;//每隔0.5ms加1,最大为100
/*函数声明*/
void PWM_Motor(int x,y); //x代表time值,y代表中间值
void Timer0_Config(); //12MHz,定时0.5ms
void main()
{
Timer0_Config();//配置定时器
while(1)
{ //白色地面,输出低电平灯亮;黑色地面,输出高电平灯灭
if(Left_Trace==0 && Mid_Trace==1 && Right_Trace==0)//若中间检测到黑线,则小车前进
{
Motor_Go();//前进
PWM_Motor(time,80);//占空比80%
if(Left_Trace==0 && Mid_Trace==0 && Right_Trace==0)
{
Motor_Rightt();//原地右转
PWM_Motor(time,100);
}
}
else if(Left_Trace==0 && Mid_Trace==0 && Right_Trace==1)//若右边检测到黑线,小车向右移动
{
Motor_Right();//右转
PWM_Motor(time,100);
}
else if(Left_Trace==0 && Mid_Trace==1 && Right_Trace==1)//若中、右边检测到黑线,小车右急弯
{
Motor_Rightt();//原地右转
PWM_Motor(time,50);
}
else if(Left_Trace==1 && Mid_Trace==0 && Right_Trace==0)//若左边检测到黑线,小车左转
{
Motor_Left();//左转
PWM_Motor(time,100);
}
else if(Left_Trace==1 && Mid_Trace==1 && Right_Trace==0)//若中、左边检测到黑线,小车左急转
{
Motor_Leftt();//原地左转
PWM_Motor(time,100);
}
else if(Left_Trace==1 && Mid_Trace==1 && Right_Trace==1)//全检测到黑色地面,灯灭,小车停止
{
Motor_Stop();//停止
}
}
}
void PWM_Motor(int x,y)//x代表time值,y代表中间值
{
if(x<y)
{
ENA = 1;
ENB = 1;
}
else
{
ENA = 0;
ENB = 0;
}
}
void Timer0_Config()//12MHz,定时0.5ms
{
TMOD = 0X01;//定时器T0,方式1
TH0 = 0XFE;
TL0 = 0X0C;//65536-X=500,X=65036=0XFE0C
EA = 1;
ET0 = 1;
TR0 = 1;
}
void Timer0()interrupt 1 using 2
{
TH0 = 0XFE;
TL0 = 0X0C;//重装初值
time++;
if(time >= 100)//time每加到100清0,
{
time = 0;
}
}
/*************将上面while(1)函数换为下面while(1)函数变为跟随********************/
// while(1)
// {
// if(Left_Follow==0 && Right_Follow==0)//正常直走跟随
// {
// Motor_Go();
// PWM_Motor(time,70);
// }
// else if(Left_Follow==0 && Right_Follow==1)//右边收不到信号,前面小车左转
// {
// Motor_Left();
// PWM_Motor(time,70);
// }
// else if(Left_Follow==1 && Right_Follow==0)//左边收不到,前面小车右转
// {
// Motor_Right();
// PWM_Motor(time,70);
// }
// else
// {
// Motor_Go();
// PWM_Motor(time,100);
// }
// }
//}
头文件#include<Motor.h>内容如下
#ifndef __Motor_H__
#define __Motor_H__
sbit IN1 = P1^2;
sbit IN2 = P1^3;//控制左两轮
sbit IN3 = P1^4;
sbit IN4 = P1^5;//控制右两轮
void Motor_Go()//前进
{
IN1 = 1;
IN2 = 0;
IN3 = 1;
IN4 = 0;
//上四句可合为一句,P1=00 0101 00=0X14;但小车很慢
}
void Motor_Back()//后退
{
IN1=0;
IN2=1;
IN3=0;
IN4=1;
}
void Motor_Left()//左转
{
IN1=0;
IN2=0;
IN3=1;
IN4=0;
}
void Motor_Leftt()//原地左转
{
IN1=0;
IN2=1;
IN3=1;
IN4=0;
}
void Motor_Right()//右转
{
IN1=1;
IN2=0;
IN3=0;
IN4=0;
}
void Motor_Rightt()//原地右转
{
IN1=1;
IN2=0;
IN3=0;
IN4=1;
}
void Motor_Stop()//停止
{
IN1=0;
IN2=0;
IN3=0;
IN4=0;
}
#endif
四、 源文件
链接:https://pan.baidu.com/s/1QGdGpW4B4PeWdR1cK6lNSw?pwd=1231
提取码:1231