51單片機串口檢測程序(C語(yǔ)言代碼)
#i nclude reg51_STC.H
#define uchar unsigned char
#define uint unsigned int
//--------------------------------------------------------------------------
//函數名稱(chēng): UART_Init()
//函數功能: 串口初始化函數,在系統時(shí)鐘為11.059MHZ時(shí),設定串口波特率為9600bit/s
//其他說(shuō)明: 串口接收中斷允許,發(fā)送中斷禁止
//--------------------------------------------------------------------------
void UART_Init(void)
{
SCON = 0x50 ; //SCON: serail mode 1, 8-bit UART, enable ucvr
TMOD |= 0x20 ; //TMOD: timer 1, mode 2, 8-bit reload
PCON |= 0x80 ; //SMOD=1;
TH1 = 0xFA ; //Baud:9600 fosc=11.0592MHz
ES=1;
TR1 = 1 ; // timer 1 run
EA=1;
}
//--------------------------------------------------------------------------
//函數名稱(chēng): main(void)
//函數功能: 主函數
//其他說(shuō)明: 無(wú)
//--------------------------------------------------------------------------
void main(void)
{
UART_Init();
while(1);
}
//--------------------------------------------------------------------------
//函數名稱(chēng): Uart_SendData()
//函數功能: 串口發(fā)送一個(gè)字節的數據
//其他說(shuō)明: 此程序供中斷調用
//--------------------------------------------------------------------------
void Uart_SendData(uchar dat)
{
SBUF=dat; //寫(xiě)SBUF,開(kāi)始發(fā)送
while(TI==0); //等待發(fā)送
TI=0; //清發(fā)送標志位
}
//--------------------------------------------------------------------------
//函數名稱(chēng): INT_UartRcv()
//函數功能: 串口接收中斷函數
//其他說(shuō)明: 無(wú)
//--------------------------------------------------------------------------
void INT_UartRcv(void) interrupt 4
{
uchar Rcv;
if(RI)
{
RI=0; //
Rcv=SBUF;
Uart_SendData(Rcv); //返回接收數據,可以改為其他函數
}
}
NO。2
#i ncludereg52.h>
#i nclude string.h>
#define INBUF_LEN 4 //數據長(cháng)度
unsigned char inbuf1[INBUF_LEN];
unsigned char checksum,count3;
bit read_flag= 0 ;
void init_serialcomm( void )
{
SCON = 0x50 ; //SCON: serail mode 1, 8-bit UART, enable ucvr
TMOD |= 0x20 ; //TMOD: timer 1, mode 2, 8-bit reload
PCON |= 0x80 ; //SMOD=1;
TH1 = 0xF4 ; //Baud:4800 fosc=11.0592MHz
IE |= 0x90 ; //Enable Serial Interrupt
TR1 = 1 ; // timer 1 run
EA=1;
}
//向串口發(fā)送一個(gè)字符
評論