📄 tongshi.c
字号:
/*-----------单片机串口接收程序-----------
-----------------------------------------*/
#include <reg52.h>
#include <string.h>
#include <INTRINS.h>
#define INBUF_LEN 7 //帧结构 同步字 地址 数据
#define uchar unsigned char
#define uint unsigned int
#define ulong unsigned long
uchar inbuf1[INBUF_LEN];
uchar MCU_ADD;
uchar recv_state=0;
uchar q; //距离
uchar a,b;
sbit p17 = P1^7;
sbit p11 = P1^1;
int cn;
int m;
uchar count3;
int time;
uchar DIR;
bit read_flag;
bit start_flag;
void Init();
void Delay(int i);
void fr(int m);
void bk(int m);
void init_serialcomm(void)
{
SCON = 0x50; //SCON: serail mode 1, 8-bit UART, enable ucvr
IE = 0x90; //EA=1,ES=1
T2CON = 0x34; //RCLK=1,TCLK=1,TR2=1
RCAP2H= 0xff;
RCAP2L= 0xd9; //12M,9600bps
}
void sendchar(unsigned char c)
{ SBUF=c;
while(TI==0);
TI=0;
}
//串口接收中断函数
void serial() interrupt 4 using 3
{
uchar data c;
if(RI)
{
RI = 0;
c=SBUF;
switch(recv_state)
{
case 0:
if(c==0x33)
{recv_state=1;
}
break;
case 1:
if(c==0x34)
{recv_state=2;
}
break;
case 2:
if(c==MCU_ADD)
{ count3=3;
recv_state=3;
}
else if(c==0xff)
{ start_flag=1;
}
else {recv_state=0;}
break;
case 3:
{ inbuf1[count3++]=c;
if(count3==INBUF_LEN)
read_flag=1;
}
break;
default:
recv_state=0;
break;
}
}
}
void bk(m)//电机反转
{
int i;
for(i=0;i<m;i++){
P2=0x10;
Delay(time);
P2=0x80;
Delay(time);
P2=0x20;
Delay(time);
P2=0x40;
Delay(time);
}
}
void fr(m)//电机正转
{
int i;
for(i=0;i<m;i++){
P2=0x10;
Delay(time);
P2=0x40;
Delay(time);
P2=0x20;
Delay(time);
P2=0x80;
Delay(time);
}
}
void Init()
{
P2=0;
Delay(100);
}
void Delay(int i)
{
int k,j;
for(k=0;k<i;k++){
for(j=0;j<50;j++);
}
}
main()
{
init_serialcomm(); //初始化串口
Init();
p17 = 0; //max485为收
MCU_ADD = 0x00; //设置地址
while(1)
{
if(read_flag)
{
read_flag=0;
a = inbuf1[3];
b = inbuf1[4];
DIR = inbuf1[5];
time = inbuf1[6];
cn = 5*(a*100+b); //5*mm的10倍
recv_state=0;
p17 = 1;
sendchar(0xfe);
p17 = 0;
}
else if(start_flag)
{
if(DIR==1)
{ //recv_state=0;
fr(cn);
P2=0;
start_flag=0;
recv_state=0;
Delay(1000);
}
else
{ // recv_state=0;
bk(cn);
P2=0;
start_flag=0;
recv_state=0;
Delay(1000);
}
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -