SƠ ĐỒ NGUYÊN LÝ:
Nguyễn Tri Bình – HCMUTE
1
Nguyễn Tri Bình – HCMUTE
2
Nguyễn Tri Bình – HCMUTE
3
LƯU ĐỒ:
Nguyễn Tri Bình – HCMUTE
4
Nguyễn Tri Bình – HCMUTE
5
CHƯƠNG TRÌNH:
#include <REGX52.H>
#define pwm_period 500
//tao xung co tan so 100ms
//Cac chan IN cua cam bien
sbit IR1=P3^3;
sbit IR2=P3^2;
sbit IR3=P3^1;
sbit IR4=P3^0;
//Dau ra de dieu khien dong co DC
sbit
EN1=P1^0;
//Right
sbit
EN2=P1^1;
//Left
sbit
IN1=P1^2;
//Right
sbit
IN2=P1^3;
//Right
sbit
IN3=P1^4;
//Left
sbit
IN4=P1^5;
//Left
sbit
START=P2^1;
//Start
unsigned char IR,dutycycleR, int_countR = 0,R,L,flag,dutycycleL, int_countL = 0;
//************************************************
void init_pwm()
{
IE=0X8A;
TMOD=0x22;
TH1=TH0=0x37; // 255-55=200us
TR1=TR0=1;
EN2=EN1=1;
}
// *************************************
void timer0(void) interrupt 1
{
int_countR++;
if (int_countR == pwm_period)
int_countR = 0;
if (int_countR <= dutycycleR) EN1 = 1;
else EN1 = 0;
}
// *************************************
void timer1(void) interrupt 3
{
int_countL++;
if (int_countL == pwm_period)
int_countL = 0;
if (int_countL <= dutycycleL) EN2 = 1;
else EN2 = 0;
}
/*// *************************************
Nguyễn Tri Bình – HCMUTE
6
void forward ()
// di thang voi do rong xung 80%
{
IN2=IN3=1;
dutycycleL=400;
dutycycleR=400;
init_pwm();
}
*/// *************************************
void turn ( unsigned char speedR,unsigned char speedL)
//re trai or phai tuy theo do
rong xung
{
IN2=IN3=1;
IN1=IN4=0;
dutycycleR=speedR;
dutycycleL=speedL;
init_pwm();
}
// *************************************
void sharpright (unsigned char speed)
//Lui trai or phai voi toc do speed
{
IN1=IN3=1;
IN2=IN4=0;
dutycycleR=speed;
dutycycleL=speed;
init_pwm();
}
//**************************************
void sharpleft (unsigned char speed) //Lui trai or phai voi toc do speed
{
IN1=IN3=0;
IN2=IN4=1;
dutycycleR=speed;
dutycycleL=speed;
init_pwm();
}
// *************************************
void run()
{
IR=P3;
IR=IR&0XFF;
//forward (); //di thang
if (IR1==0)
{
sharpright(200);
Nguyễn Tri Bình – HCMUTE
//turn right
7
flag=1;
}
else if (IR4==0)
{
sharpleft(200);
//turn left
flag=2;
}
else if (IR2==1 && IR3==1)
{
turn(400,400);
}
else if (IR==0X0FF)
{
if(flag == 1)
sharpright(400);
else if (flag == 2)
sharpleft(400);
else
turn(400,400);
}
else if (IR2==0||IR3==0)
{
turn(400,400);
flag = 0;
}
}
// *************************************
void main()
{
P1=0X00;
while (START!=0)
{
}
P3=0x00;
while (START==0)
{
}
while (START!=0)
{
run();
}
while (START==0)
{
}
}
Nguyễn Tri Bình – HCMUTE
8