单片机如何接收字符串,并发送回计算机?要求接收3个字节,下面是我写的程序,总出错

#include<reg52.h>
#define uint unsigned int
#define uchar unsigned char
/************定义全局变量**********************/
uchar data table[3];//暂存数组,2bit,"2"表示table里含有两个元素,
// 可以将2改为需要的数值,串口接收字符串数据
//data可以省略
uchar n; //串口接收字符串个数
/************函数声明**************************/
void delay(uint xms); //xms延时函数
void uart_arrive(); //串口接收字符串数据函数

/************延时xms函数**************************************/
void delay(uint xms)
{
uint m,n;
for(m=xms;m>0;m--)
for(n=110;n>0;n--);
}

/******* 串行口传送数据 传送显示数组各字符给计算机 ************/
void send(uchar *dis)
{
while(*dis!='\0')
{ SBUF=*dis;
dis++;
while(!TI);
TI=0; //软件请发送中断
}
}
/***********串口接收字符串数据函数***********************************/
void uart_arrive()
{
while(RI == 0); //接收完数据,接收标志位清零
{
RI = 0;
table[n]=SBUF; // 将接收缓冲器中的数据取出来,存到暂存数组table中
n++;
if(n==3) //当接收数量达到规定值2时,接收数清0
n=0;

}
}

/***********串口初始化****************/
void init_uart()
{
TMOD = 0x20; // 定时器1工作于8位自动重载模式, 用于产生波特率
TH1=0xfd; //波特率9600
TL1=0xfd;

SCON = 0x50;
PCON = 0x00;
TR1 = 1;
ES=1;
EA=1;
}
/***********主函数****************************************************/
/***********主函数****************************************************/
void main(void)
{
init_uart();

while(1)
{
uart_arrive();//串口接收字符串数据
send(table);
delay(1);
}
}

第1个回答  2014-06-05
你的程序接收部分有点问题啊,错误如下:
/***********串口接收字符串数据函数***********************************/
void uart_arrive()
{
while(RI == 0); 后面多了个分号,这种判断是错误的,应该RI == 1
{
RI = 0;
table[n]=SBUF; // 将接收缓冲器中的数据取出来,存到暂存数组table中
n++;
if(n==3) //当接收数量达到规定值2时,接收数清0
n=0;

}
}

上面的程序接收判断while(RI== 0)这句有问题,正确如下:

while(RI ) //接收完数据,接收标志位清零
{
RI = 0;
table[n]=SBUF; // 将接收缓冲器中的数据取出来,存到暂存数组table中
n++;
f(n==3) //当接收数量达到规定值2时,接收数清0
{
n=0;
}

}追问

还是不行,接收部分还是不对劲,您能给我一个串口接收字符串的函数吗?万分感谢

追答

这两天一直很忙,我今天晚上刚好闲帮你写一个程序,可以接收字符串
/*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
*
**/
#include "STC89C5X.H"

unsigned char UARTByte[4];
bit Flag_Error;
unsigned char Max_Byte = 0;

/*
* 系统初始化
*/
void SystemInit(void)
{
// IO初始化
P0 = 0xFF;
P1 = 0xFF;
P2 = 0xFF;
P3 = 0xFF;

// 配置UART
PCON&= 0x7F;
TCON = 0x00;
SCON = 0x50;

// 配置T2
TMOD = 0x20;
//
TH1 = 0xFD;
TL1 = 0xFD;
//
TR1 = 1;
ES = 1;
EA = 1;
}

/*
* UART发送一个字节数据
*/
void UART_Send_Byte(unsigned char Byte)
{
ES = 0;
TI = 0;
SBUF = Byte;
while(!TI);
TI = 0;
ES = 1;
}

/*
* 函数主题
*/
int main(void)
{
unsigned char i;

SystemInit();

while(1)
{
if(Flag_Error)
{
for(i = 0; i < 4; i++)
{
UART_Send_Byte(UARTByte[i]);
}
Flag_Error = 0;
Max_Byte = 0;
}
}
}

/*
* UART中断服务程序
*/
void UART_IRQ(void) interrupt 4
{
// unsigned char t;

if(RI)
{
RI = 0;
UARTByte[Max_Byte] = SBUF;
Max_Byte++;
if(Max_Byte == 4)
{
Flag_Error = 1;
}
}
}

相似回答