單片機技術C51串口輸出輸入函數(shù)
ComFun.c
C51串口輸出輸入函數(shù)
外部聲明 ComFun.h
----------------------------------------*/
#include
//串口初始化 晶振為11.0592M 方式1 波特率300-57600
void InitCom(unsigned char BaudRate)
{
unsigned char THTL;
switch (BaudRate)
{
case 1: THTL = 64; break; //波特率300
case 2: THTL = 160; break; //600
case 3: THTL = 208; break; //1200
case 4: THTL = 232; break; //2400
case 5: THTL = 244; break; //4800
case 6: THTL = 250; break; //9600
case 7: THTL = 253; break; //19200
case 8: THTL = 255; break; //57600
default: THTL = 208;
}
SCON = 0x50; //串口方式1,允許接收
TMOD = 0x20; //定時器1定時方式2
TCON = 0x40; //設定時器1開始計數(shù)
TH1 = THTL;
TL1 = THTL;
PCON = 0x80; //波特率加倍控制,SMOD位
RI = 0; //清收發(fā)標志
TI = 0;
TR1 = 1; //啟動定時器
}
//向串口輸出一個字符(非中斷方式)
void ComOutChar(unsigned char OutData)
{
SBUF = OutData; //輸出字符
while(!TI); //空語句判斷字符是否發(fā)完
TI = 0; //清TI
}
//向串口輸出一個回車換行
void ComOutEnter(void)
{
SBUF = 0x00;
while(!TI);
TI = 0;
SBUF = 0x0A;
while(!TI);
TI = 0;
}
//向串口輸出一個字符串(非中斷方式)
void ComOutStr(unsigned char *Str)
{
while(*Str != 0x00) //判斷是否到了字符串的尾部
{
SBUF = *Str; //輸出字符
while(!TI); //空語句判斷字符是否發(fā)完
TI = 0; //清TI
Str++; //字符串指針加一
}
}
//從串口接收一個字符(非中斷方式)
unsigned char ComInChar()
{
unsigned char InData;
while(!RI); //空語句判斷字符是否收完
InData = SBUF; //保存COM緩沖字符
RI = 0; //清RI
return (InData); //返回收到的字符
}
//從串口接收一個定長字符串(非中斷方式,只用于字符需有一個的idata字符串數(shù)組)
//如unsigned char *Str;
//unsigned char i[]="abcd";
//InHandStr = &i;
void ComInStr(unsigned char *Str)
{
while(*Str != 0x00) //判斷是否到了字符串的尾部
{
while(!RI); //空語句判斷字符是否收完
*Str = SBUF; //保存字符
RI = 0; //清RI
Str++; //字符串指針加一
}
}
評論