51單片機(jī)串口檢測(cè)程序(C語言代碼)
#i nclude reg51_STC.H
#define uchar unsigned char
#define uint unsigned int
//--------------------------------------------------------------------------
//函數(shù)名稱: UART_Init()
//函數(shù)功能: 串口初始化函數(shù),在系統(tǒng)時(shí)鐘為11.059MHZ時(shí),設(shè)定串口波特率為9600bit/s
//其他說明: 串口接收中斷允許,發(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;
}
//--------------------------------------------------------------------------
//函數(shù)名稱: main(void)
//函數(shù)功能: 主函數(shù)
//其他說明: 無
//--------------------------------------------------------------------------
void main(void)
{
UART_Init();
while(1);
}
//--------------------------------------------------------------------------
//函數(shù)名稱: Uart_SendData()
//函數(shù)功能: 串口發(fā)送一個(gè)字節(jié)的數(shù)據(jù)
//其他說明: 此程序供中斷調(diào)用
//--------------------------------------------------------------------------
void Uart_SendData(uchar dat)
{
SBUF=dat; //寫SBUF,開始發(fā)送
while(TI==0); //等待發(fā)送
TI=0; //清發(fā)送標(biāo)志位
}
//--------------------------------------------------------------------------
//函數(shù)名稱: INT_UartRcv()
//函數(shù)功能: 串口接收中斷函數(shù)
//其他說明: 無
//--------------------------------------------------------------------------
void INT_UartRcv(void) interrupt 4
{
uchar Rcv;
if(RI)
{
RI=0; //
Rcv=SBUF;
Uart_SendData(Rcv); //返回接收數(shù)據(jù),可以改為其他函數(shù)
}
}
NO。2
#i ncludereg52.h>
#i nclude string.h>
#define INBUF_LEN 4 //數(shù)據(jù)長度
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è)字符
評(píng)論