串列編程計算
1. PIC單片機16F883 串列非同步通信 c語言編程 請詳細寫出各個寄存器,串口的作用,謝謝了。
#include <pic.h>
#define FOSC 18432000L
#define BAUD 115200
#define NONE_PARITY 0 //無校驗位
#define ODD_PARITY 1 //奇校驗
#define EVEN_PARITY 2 //偶校驗
#define MARK_PARITY 3 //標記校驗
#define SPACE_PARITY 4 //空校驗
#define PARITYBIT EVEN_PARITY
#define S2RI 0x01
#define S2TI 0x02
#define S2RB8 0x04
#define S2TB8 0x08
sfr AUXR = 0x8e;
sfr S2CON = 0x9a;
sfr S2BUF = 0x9b;
sfr BRT = 0x9c;
sfr IE2 = 0xaf;
bit busy;
void SendData(char dat);
void SendString(char *s);
void main()
{
#if (PARITYBIT == NONE_PARITY)
S2CON = 0x5a; //8位可變波特率 (無校驗位)
#elif (PARITYBIT == ODD_PARITY) || (PARITYBIT == EVEN_PARITY) || (PARITYBIT == MARK_PARITY)
S2CON = 0xda; //9位可變波特率,校驗位初始為1
#elif (PARITYBIT == SPACE_PARITY)
S2CON = 0xd5; //9位可變波特率,校驗位初始為0
#endif
BRT = -(FOSC/32/BAUD); //設置獨立波特率發生器的重載初值
AUXR = 0x14; //獨立波特率發生器工作在1T模式
IE2 = 0x01; //使能串口2中斷
EA = 1; //開總中斷
SendString("STC12C5A60S2\r\nUart2 Test !\r\n");
while(1);
}
void Uart2() interrupt 8 using 1
{
if (S2CON & S2RI)
{
S2CON &= ~S2RI; //清除接收完成標志
P0 = S2BUF; //P0顯示串口數據
P2 = (S2CON & S2RB8); //P2.2顯示校驗位
}
if (S2CON & S2TI)
{
S2CON &= ~S2TI; //清除發送完成標志
busy = 0;
}
}
void SendData(char dat)
{
while (busy); //等待上個數據發送完成
ACC = dat; //取得偶校驗位P
if (P) //根據P來設置串口數據的校驗位
{
#if (PARITYBIT == ODD_PARITY)
S2CON &= ~S2TB8; //置校驗位為0
#elif (PARITYBIT == EVEN_PARITY)
S2CON |= S2TB8; //置校驗位為1
#endif
}
else
{
#if (PARITYBIT == ODD_PARITY)
S2CON |= S2TB8; //置校驗位為1
#elif (PARITYBIT == EVEN_PARITY)
S2CON &= ~S2TB8; //置校驗位為0
#endif
}
busy = 1;
S2BUF = ACC; //發送數據
}
void SendString(char *s)
{
while (*s) //判斷字元串結束標志
{
SendData(*s++); //發送字元
}
}