新闻中心

EEPW首页>嵌入式系统>设计应用> 智能小车C语言程序

智能小车C语言程序

作者: 时间:2016-11-23 来源:网络 收藏
智能小车黑线循迹C语言程序
#include
#include
#define uchar unsigned char
#define uint unsigned int

sbit LeftIR=P1^6; //左边红外接收
sbit RightIR=P1^7; //右边红外接收
sbit ENA=P1^2; // L298的Enable A
sbit IN1=P1^0; // L298的Input 1
sbit IN2=P1^1; // L298的Input 2
sbit ENB=P1^5; // L298的Enable B
sbit IN3=P1^3; // L298的Input 3
sbit IN4=P1^4; // L298的Input 4
uchar t=0; //中断计数器
uchar motor_1=0,motor_2=0; //电机1,2速度值
uchar tmp1,tmp2; // 电机当前速度值
uchar aa; //定时器1中断计数
bit flag=0; //标志位


void motor(uchar index, char speed)
{
if(speed>=-100 && speed<=100)
{
if(index==1) // 电机1的处理
{
motor_1=abs(speed); // 取速度的绝对值
if(speed<0) // 速度值为负则反转
{
IN1=0;
IN2=1;
}
else // 不为负数则正转
{
IN1=1;
IN2=0;
}
}
if(index==2) // 电机1的处理
{
motor_2=abs(speed); // 取速度的绝对值
if(speed<0) // 速度值为负则反转
{
IN3=0;
IN4=1;
}
else // 不为负数则正转
{
IN3=1;
IN4=0;
}
}
}
}
void init()
{
TMOD=0x12; // 设定T0的工作模式为2
TH0=0x9B; // 装入定时器的初值
TL0=0x9B;
TH1=(65536-50000)/256; //设置初值定时50ms
TL1=(65536-50000)%6;
EA=1; // 开中断
ET0=1; // 定时器0允许中断
ET1=1; //定时器1允许中断
TR0=0; // 关闭定时器0
TR1=0; // 关闭定时器0
ENA=0; //关闭电机1
ENB=0; //关闭电机2
}
void main()
{
int irDetectLeft,irDetectRight;
init();
while(1)// 电机实际控制演示
{
irDetectRight = RightIR;//右边接收
irDetectLeft = LeftIR;//左边接收
if((irDetectLeft==0)&&(irDetectRight==0))//向前进
{
motor(1,100);
motor(2,100);
}
if((irDetectLeft==0)&&(irDetectRight==1))//右转
{
motor(1,-100);
motor(2,100);
}
if((irDetectLeft==1)&&(irDetectRight==0))//左转
{
motor(1,100);
motor(2,-100);
}
if((irDetectLeft==1)&&(irDetectRight==1)&&(flag==0)) //第一次探测定时器1开始计时
{
motor(1,100);
motor(2,100);
TR1=1;
}
if((irDetectLeft==1)&&(irDetectRight==1)&&(flag==1))//第二次探测时小车停
{
TR0=0;
ENA=0;
ENB=0;
}
}
}
void timer0() interrupt1 // T0中断服务程序
{
if(t==0) // 1个PWM周期完成后才会接受新数值
{
tmp1=motor_1;
tmp2=motor_2;
}
if(t ENA=1;
else
ENA=0; // 产生电机1的PWM信号
if(t ENB=1;
else
ENB=0; // 产生电机2的PWM信号
t++;
if(t>=100)
t=0; // 1个PWM信号由100次中断产生
}
void timer1() interrupt 3
{
TH1=(65536-50000)/256;
TL1=(65536-50000)%6;
aa++;
if(aa==40) //定时2s后小车开始运动
TR0=1;
if(aa==60) //定时3s后置标志位
{
aa=0;
flag=1;
}
}


评论


技术专区

关闭