//這是一個單片機C51串口接收(中斷)和發(fā)送例程,可以用來測試51單片機的中斷接收//和查詢發(fā)送,另外我覺得發(fā)送沒有必要用中斷,因為程序的開銷是一樣
#include
#include
#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
// TI="1";
}
//向串口發(fā)送一個字符
void send_char_com(unsigned char ch)
{
SBUF="ch";
while(TI==0);
TI=0;
}
//向串口發(fā)送一個字符串,strlen為該字符串長度
void send_string_com(unsigned char *str,unsigned int strlen)
{
unsigned int k=0;
do
{
send_char_com(*(str + k));
k++;
} while(k < strlen);
}
//串口接收中斷函數(shù)
void serial () interrupt 4 using 3
{
if(RI)
{
unsigned char ch;
RI = 0;
ch="SBUF";
if(ch>127)
{
count3=0;
inbuf1[count3]=ch;
checksum= ch-128;
}
else
{
count3++;
inbuf1[count3]=ch;
checksum ^= ch;
if( (count3==(INBUF_LEN-1)) && (!checksum) )
{
read_flag=1; //如果串口接收的數(shù)據(jù)達到INBUF_LEN個,且校驗沒錯,
//就置位取數(shù)標志
}
}
}
}
main()
{
init_serialcomm(); //初始化串口
while(1)
{
if(read_flag) //如果取數(shù)標志已置位,就將讀到的數(shù)從串口發(fā)出
{
read_flag=0; //取數(shù)標志清0
send_string_com(inbuf1,INBUF_LEN);
}
}
}
本文引用地址:http://m.butianyuan.cn/article/201611/320296.htm
評論