串口通信-數(shù)據(jù)發(fā)送到PC加1后接收到單片機(jī)在數(shù)碼管上顯示
/**
*功能:串口通信-數(shù)據(jù)發(fā)送到PC加一后接收到單片機(jī)在數(shù)碼管上顯示
*時(shí)間:2014年3月2日10:04:07
*作者:寒竹子
*備注:波特率:19200bps
*總結(jié):串口通信時(shí)需要發(fā)送和接收數(shù)據(jù)時(shí)可以用到串口中斷,在中斷中進(jìn)行數(shù)據(jù)的發(fā)送和接收,
* 數(shù)碼管顯示時(shí)必須要放在while (1)中,只有這樣才可以正常顯示數(shù)字!
**/
#include
typedef unsigned int uint;
typedef unsigned char uchar;
//數(shù)碼管段選和位選聲明
sbit WELA = P2^7;
sbit DULA = P2^6;
//數(shù)碼管編碼
uchar code table[] = {
0x3F, //"0"
0x06, //"1"
0x5B, //"2"
0x4F, //"3"
0x66, //"4"
0x6D, //"5"
0x7D, //"6"
0x07, //"7"
0x7F, //"8"
0x6F //"9"
};
uint num = 254;
void UART_init();
void UART_init();
void display(uint num);
int main(void)
{
UART_init();
WELA = 1;
P0 = 0xFF;
WELA = 0;
DULA = 1;
P0 = 0x00;
DULA = 0;
while (1)//等待串口發(fā)送和接收數(shù)據(jù)中斷
{
//在數(shù)碼管上顯示
display(num);//數(shù)碼管顯示是動(dòng)態(tài)顯示的,所以必須要放在while (1)循環(huán)中,這樣才可以動(dòng)態(tài)顯示!
P1 = num;
}
return 0;
}
//串口通信初始化(定時(shí)器T1初始化和串口通信方式的選擇)
void UART_init()
{
//設(shè)定T1定時(shí)器工作方式2,八位自動(dòng)重裝,用于設(shè)定串口通信波特率
TMOD = 0x20;//T1: GATE C/!T 0 0 M1 M0:10 T0:0000
//設(shè)定波特率19200bps 初值 X = 2^8 - 11059200 / 19200 / 12 /32; X = 254.5 0xFE
TH1 = TL1 = 0xFE;
TR1 = 1;//打開(kāi)定時(shí)器T1
SCON = 0x50;//設(shè)定串口通信方式1,八位異步傳輸波特率可設(shè)定
/*
SM0 = 0;
SM1 = 1;//方式1
REN = 1;//允許接收
*/
//因?yàn)橐M(jìn)行發(fā)送和接收,需要用到串口中斷
EA = 1;//開(kāi)總中斷
ES = 1;//開(kāi)定時(shí)器T1中斷
}
//延時(shí)xms
void delayms(uint xms)
{
uint i, j;
for (i = 0; i < xms; i++)
for (j = 0; j < 110; j++);
}
//數(shù)碼管顯示
void display(uint num)
{
//將num分解
uchar bai, shi, ge;
bai = num / 100 % 10;
shi = num / 10 % 10;
ge = num % 10;
//先段選后位選
DULA = 1;//打開(kāi)段選鎖存器
P0 = table[ge];//送入個(gè)位
DULA = 0;//關(guān)閉段選鎖存器
P0 = 0xFF;//先關(guān)閉所有數(shù)碼管的顯示,避免亂碼
WELA = 1;//打開(kāi)位選鎖存器
P0 = 0xDF;//1101 1111
WELA = 0;//關(guān)閉位選鎖存器
//延時(shí)3毫秒
delayms(3);
P0 = 0x00;//消影
//十位
DULA = 1;
P0 = table[shi];
DULA = 0;
P0 = 0xFF;
WELA = 1;
P0 = 0xEF; //1110 1111
WELA = 0;
delayms(3);
P0 = 0x00;
//百位
DULA = 1;
P0 = table[bai];
DULA = 0;
P0 = 0xFF;//關(guān)閉所有數(shù)碼管,避免段選數(shù)據(jù)的影響
WELA = 1;
P0 = 0xF7; //1111 0111
WELA = 0;
delayms(3);
P0 = 0x00;//消影
}
//串口通信中斷
void UART_sendAndReceive_int() interrupt 4//串口中斷號(hào)4
{
//判斷發(fā)送和接收的完成
if (TI)//硬件置位,發(fā)送數(shù)據(jù)完成
{
TI = 0;//TI清零,等待發(fā)送下一位數(shù)據(jù)
//允許接收數(shù)據(jù)
REN = 1;
}
//接收
if (RI)//接收完成
{
RI = 0;//RI清零,等待接收下一位數(shù)據(jù)
//取出SBUF中的數(shù)據(jù)
num = SBUF;
//num++
num++;
//禁止接收數(shù)據(jù)
REN = 0;
SBUF = num;//發(fā)送num
}
}
評(píng)論