#include<reg52.h>
#include"pwm.h"
void main()
{
unsigned char i;
P1=0X00; //关电车电机
B: for(i=0;i<50;i++)
{
delay(1);
if(P3^7!=0)
goto B;
}
BUZZ=0; //50次检测K4确认是按下之后,蜂鸣器发出“滴”声响,然后启动小车。
delay(50);
BUZZ=1;//响50ms后关闭蜂鸣器
TMOD=0X01;
TH0= 0XFc; //1ms定时
TL0= 0X18;
TR0= 1;
ET0= 1;
EA = 1; //工作模式设定
while(1)
{ //有信号为0,无信号为1
if(Left_led == 1 && Left_led == 1)
{
run();
}
else if(Left_led == 0 && Right_led == 1)
{
rightrun();
}
else if(Left_led == 1 && Right_led == 0)
{
leftrun();
}
else
{
backrun();
delay(500);
leftrun();
delay(20);
}
}
}
#ifndef _PWM_H_
#define _PWM_H_
sbit IN1 = P1^2;
sbit IN2 = P1^3;
sbit IN3 = P1^6;
sbit IN4 = P1^7;
sbit EN1 = P1^4;
sbit EN2 = P1^5;
sbit BUZZ = P2^3;//蜂鸣器
#define Left_led P3^5//左传感器
#define Right_led P3^4//右传感器
#define Left_pwm P1^5//左电机使能
#define Right_pwm P1^4//右电机使能
#define Left_moto_go {IN1=0,IN2=1;}//左电机前进
#define Left_moto_back {IN1=1,IN2=0;}//左电机后退
#define Right_moto_go {IN3=1,IN4=0;}//右电机前进
#define Right_moto_back {IN3=0,IN4=1;}//右电机后退
#define Left_moto_stop {EN2 = 0;}//左电机停止
#define Right_moto_stop {EN1 = 0;}//右电机停止
unsigned char Left_val_pwm = 0;
unsigned char Right_val_pwm = 0;
unsigned char Left_compare_pwm = 0;//左电机占空比
unsigned char Right_compare_pwm = 0;//右电机占空比
unsigned int time = 0;
//延时函数
void delay(unsigned int k)
{
unsigned int x,y;
for(x=0;x<k;x++)
for(y=0;y<2000;y++);
}
//前进
void run()
{
Left_compare_pwm=10; //速度调节变量 0-20。。。0最小,20最大
Right_compare_pwm=10;
Left_moto_go ; //左电机往前走
Right_moto_go ; //右电机往前走
}
//后退
void backrun()
{
Left_compare_pwm=8; //速度调节变量 0-20。。。0最小,20最大
Right_compare_pwm=8;
Left_moto_back; //左电机往后退
Right_moto_back; //右电机往后退
}
//左转
void leftrun()
{
Right_compare_pwm=8;
Right_moto_go; //右电机往前走
Left_moto_stop; //左电机停止
}
//右转
void rightrun()
{
Left_compare_pwm=8;
Left_moto_go ; //左电机往前走
Right_moto_stop ; //右电机
}
//左电机pwm调速
void pwm_moto_left()
{
if(Left_val_pwm >20)
Left_val_pwm = 0;
if(Left_val_pwm <= Left_compare_pwm)
Left_pwm = 1;
else
Left_pwm = 0;
}
//右电机pwm调速
void pwm_moto_right()
{
if(Right_val_pwm >20)
Right_val_pwm = 0;
if(Right_val_pwm <=Right_compare_pwm)
EN1 = 1;
else
EN1 = 0;
}
void timer0() interrupt 1
{
TH0=0XFc; //1Ms定时
TL0=0X18;
time++;
Left_val_pwm++;
Right_val_pwm++;
pwm_moto_right();
pwm_moto_left();
}
#endif
|