📄 serial.c
字号:
#include "typedef.h"
#include "ExtDef.h"
#define LenTxBuf 2000
#define LenRxBuf 50
#define MaxLenStr 100
#define TABNum 8
uchar xdata TxBuf[LenTxBuf],RxBuf[LenRxBuf]; // buffer entities,缓冲区实体
uchar xdata *inTxBuf,*outTxBuf,*inRxBuf,*outRxBuf; // buffer pointers,缓冲区指针
uchar TIflag;
uchar RIflag;
void InitSerialBuffer(void)
{
inTxBuf = TxBuf;
outTxBuf = TxBuf;
inRxBuf = RxBuf;
outRxBuf = RxBuf+LenRxBuf-1;
}
void InitSerial(unsigned char BaudRate)
{
unsigned char THTL;
switch (BaudRate)
{
case 1: THTL = 64; break; //波特率300
case 2: THTL = 160; break; //600
case 3: THTL = 208; break; //1200
case 4: THTL = 232; break; //2400
case 5: THTL = 244; break; //4800
case 6: THTL = 250; break; //9600
case 7: THTL = 253; break; //19200
case 8: THTL = 255; break; //57600
default: THTL = 208;
}
/* SCON = 0x52; set TI to 1, this is important for printf();if SCON=0x50,printf() function doesn't work!*/
SCON = 0x52; //串口方式1,允许接收 ; SM0|SM1|SM2|REN|TB8|RB8|TI|RI ,
// SM0|SM1 used to define work mode; 00:Mode0(SPI);
// 01:Mode1,8bit URAT(T1 Band Generator);
// 10:Mode2,9bit URAT(Bandrate fsoc/64,fsoc/32;
// 11:Mode3,9bit URAT(T1 Bandrate Generator);
// SM2=1:multi machines communication;
// REN=1: Receive enable;
// TB8: the TX nineth bit; RB8: the RX nineth bit
TMOD = 0x20; //定时器1定时方式2; Gate | C/T | M1 | M0 | Gate | C/T | M1 | M0
// Gate:external start/stop control , controlled by P3.2(INT0) or P3.3(INT1)
// C/T: =0:internal timer ; =1:external counter;
// M1|M0: 00: 13bits counter/timer;
// 01: 16bits counter/timer;
// 10: auto reload 8bits counter/timer;
// 11: only fits to T0;two 8bits counter/timer;
TCON = 0x00;
TH1 = THTL;
TL1 = THTL;
PCON = 0x80; //波特率加倍控制,SMOD位
ES = 1; // enable URAT interrupt.
TR1 = 1; //启动定时器
}
void PrintChar(uchar ch)
{
uchar *t;
t=inTxBuf; t++;
if(t==TxBuf+LenTxBuf)
t=TxBuf; //Rotate pointer
if(t==outTxBuf)
return; //Tx Buffer is full
*inTxBuf = ch;
inTxBuf = t;
if(TIflag)
{
TIflag = 0;
TI=1;
}
}
void PrintStr(uchar *str)
{
uchar i;
uchar j;
uchar ch;
for(i=0;i<MaxLenStr;i++)
{
ch=*(str+i);
if(ch=='\0')
break;
else
if(ch=='\n')
{
PrintChar(10);
PrintChar(13);
}
else
if(ch=='\t')
{
for(j=0;j<TABNum;j++)
PrintChar(' ');
}
else
PrintChar(ch);
}
}
void clrscr()
{
PrintStr("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
}
void serial()
{
uchar *t;
if(TI)
{
TI=0;
if(inTxBuf==outTxBuf)
{
TIflag=1;
return;
} // Tx buffer is empty.
SBUF = *outTxBuf;
outTxBuf++;
if(outTxBuf==TxBuf+LenTxBuf)
outTxBuf=TxBuf;
}
if(RI)
{
RI=0;
if(!RIflag)
RIflag=1;
t=inRxBuf;
t++;
if(t==RxBuf+LenRxBuf) t=RxBuf;
if(t==outRxBuf) return; // Rx buffer is full.
*inRxBuf=SBUF;
inRxBuf=t;
}
}
void URAT_ISR() interrupt 4
{
serial();
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -