#include<reg52.h>
sbit IN1=P1^0; //單片機引腳的定義
sbit IN2=P1^1;
sbit IN3=P1^2;
sbit IN4=P1^3;
#define Left_moto_go {IN1=0,IN2=1;} //小車運動的正反轉電平設置
#define Left_moto_back {IN1=1,IN2=0;}
#define Left_moto_Stop {IN1=0,IN2=0;}
#define Right_moto_go {IN3=0,IN4=1;}
#define Right_moto_back {IN3=1,IN4=0;}
#define Right_moto_Stop {IN3=0,IN4=0;}
unsigned int mode; //用數字或字符來作為運行的指令
unsigned int flag;
void delay(unsigned int k)
{
unsigned int x,y;
for(x=0;x<k;x++)
for(y=0;y<2000;y++);
}
void run(void) //與前面循跡小車項目類似定義小車運動的函數
{
Left_moto_go ;
Right_moto_go ;
}
void backrun(void)
{
Left_moto_back;
Right_moto_back;
}
void leftrun(void)
{
Right_moto_go ;
Left_moto_Stop ;
}
void rightrun(void)
{
Left_moto_go ;
Right_moto_Stop ;
}
void stop(void)
{
Right_moto_Stop ;
Left_moto_Stop ;
}
void time1init() // 選擇使用定時器1;
{
TMOD=0x20; //并且工作模式2,8位
TH1=0xfd; //產生9600波特率,與藍牙模塊同步 ,因為當時購買的藍牙模塊出廠設置就是9600波特率。
TL1=0xfd;
SM0=0; //設置串口的工作模式為
SM1=1; //傳送8位數據
REN=1; //串口通信允許接收
TR1=1; //開定時器1
EA=1; //允許總中斷
ES=1; //允許串口中斷
}
void init() interrupt 4 //4模式是串行口中斷:串行通信完成數據發送或接收
//并且引起中斷
{
RI=0; //接收中斷標志
mode=SBUF; //接收到的有手機app發送的緩沖區數據SBUF復制給mode
flag=1; //說明已經接收數據完畢
}
int main()
{
time1init();
while(1)
{
if(flag)
{
flag=0;
if(mode==1) //現在大部分都是用字符,即字母作為串口通信的數據,這里我采用了數字作為通信,
{ //大大簡化了代碼
run();
delay(20); //通過不斷調試,最后確定的延遲函數
}
if(mode==3)
{
backrun();
delay(20);
}
if(mode==4)
{
leftrun();
delay(10);
}
if(mode==5)
{
rightrun();
delay(10);
}
if(mode==2)
{
stop();
delay(40);
}
}
}
}
后面還會陸續更新藍牙手機app軟件的制作方法,敬請留意~
|