?
?
?單片機一般采用中斷方式接受數(shù)據(jù),這樣便于及時處理
#include "reg51.h"
#include "myheader.h"
#define uchar unsigned char
int szc[10]={0xc0,0xf9,0xa4,0xb0,0x99,0x92,0x82,0xf8,0x80,0x90};
int bufferc[6]={0};
int sza[6]={0x01,0x02,0x04,0x08,0x10,0x20};
void display()
{
uchar i=0;
uchar num=0;
for(i=0;i<6;i++)
{
num=bufferc[i];
P2=szc[num];
P1=sza[i];
sleep(100);
P2=0xff;
}
}
void main()
{
TMOD=0x20;
TH1=0XF4;//根據(jù)波特率計算公式這里需要設(shè)置為這么多才能夠在串行數(shù)據(jù)傳輸模式1的狀況下實現(xiàn)波特率2400B/S
TL1=0XF4;
TR1=1;
SCON=0x40;//串口工作與方式1,定義了傳送數(shù)據(jù)的格式
EA=1;
ES=1; //串口中斷開關(guān)打開
REN=1;
while(1)
{
display();
}
}
void int_4() interrupt 4
{
static uchar i=0;
EA=0;
bufferc[i]=SBUF;
i++;
if(i==6)i=0;
RI=0;
EA=1;
}
void sleep(long int a)
{
uchar i=0;
for(i=0;i<a;i++)
{
;
}
}
#include "reg51.h"
#include "myheader.h"
#define uchar unsigned char
long int sleep_i=0;
long int main_i=0;
void main()
{
uchar sendx[6]={2,0,2,3,8,1};
sleep(2000);
TMOD=0x20;
TH1=0XF4;//根據(jù)波特率計算公式這里需要設(shè)置為這么多才能夠在串行數(shù)據(jù)傳輸模式1的狀況下實現(xiàn)波特率2400B/S
TL1=0XF4;
TR1=1;
SCON=0X40;
for(main_i=0;main_i<6;main_i++)
{
SBUF=sendx[main_i];
while(TI==0);//這個是清除發(fā)送的中斷,不是清除鬧鐘中斷
TI=0;
}
while(1);
}
void sleep(long int a)
{
for(sleep_i=0;sleep_i<a;sleep_i++)
{
;
}
}
其中發(fā)送數(shù)據(jù)段采用的是查詢方式,接收端采用了中斷方式,
要注意的地方有:
在中斷處理函數(shù)int_0()內(nèi),處理數(shù)據(jù)前要先關(guān)閉中斷,否則中斷可能會不斷傳過來,
EA=0;
然后退出中斷處理函數(shù)前恢復(fù)中斷處理能力:
EA=1;
另外再main函數(shù)內(nèi)比較查詢方式要添加:
EA=1;
ES=1;文章來源:http://www.zghlxwxcb.cn/news/detail-649475.html
因為既然使用中斷,一定要把中斷中開關(guān)和serial通訊開關(guān)打開文章來源地址http://www.zghlxwxcb.cn/news/detail-649475.html
到了這里,關(guān)于c51單片機串口通信(中斷方式接收數(shù)據(jù))(單片機--單片機通信)示例代碼 附proteus圖的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!