//串口的初始化
//波特率为9600,8位数据格式,无校验,一个停止位,用查询方式发送
void SCI_Init(void)
{
SCI0BDH = 0x00;
SCI0BDL = 0x41; //波特率=BUSCLK/(16*BR[12:0])=38400 , BUSCLK=40MHz 14400_0xae 38400_0x41 230400_0x0b
SCI0CR2 = 0x2C; //发送,接收允许,接收采用中断方式
}
//将8位二进制数转换为相应的ASCII字符
unsigned char Digit_ASCII(unsigned char temp)
{
if(temp>=0x0A)//如查temp有两位,如11,则转换为B
temp = temp + 'A' - 0x0A;//'A'=65, 0x0A=10,
else
temp = temp + '0'; //temp为数字0~9, 只有1位
return temp;
}
//发送单个字符,下面这两个函数均可以
void SCI_SendChar(unsigned char ch)
{
while(SCI0SR1_TC == 0); //keep waiting when not empty
SCI0DRL = ch;
}
//或者
void SCI_SendChar(unsigned char ch)
{
while(SCI0SR1_TDRE == 0); //keep waiting when not empty
SCI0DRL = ch;
}
//通过SCI发送字符串
void SCI_SendStr(char *str)
{
while(*str!=0)
SCI_SendChar(*str++);
}
//把一个8位数以ASCII形式通过SCI0发送去
void SCI_SendHex8(unsigned char a)
{
unsigned char b;
b = (unsigned char)(a/0x10);//取8位数的高4位,低估位为0,如0xf1/0x10 = 0xf0
b = Digit_ASCII(b);
SCI_SendChar(b);
b = (unsigned char)(a%0x10);//取8位数的低4位,高4位为0, 如0xf1%0x10 = 0x01;
b = Digit_ASCII(b);
SCI_SendChar(b);
}
//把一个8位无符号数以十进制的形式发送出去
void SCI_SendDec8u(unsigned char a)
{
unsigned char b;
b = (unsigned char)(a/100);//取百位
b = b + '0';
SCI_SendChar(b);
a = a%100;
b = (unsigned char)(a/10);//取十位
b = b + '0';
SCI_SendChar(b);
b = (unsigned char)(a%10);//取个位
b = b + '0';
SCI_SendChar(b);
}
//将一个16位数以ASCII形式发送出去
void SCI_SendHex16(unsigned int a)
{
SCI_SendHex8((unsigned char)(a>>8));//即temp = a>>8; 先传a的高8位
SCI_SendHex8((unsigned char)a); //后传a的低8位,(一个16位的数赋值给一个8位的变量,只取低8位,高8位自动丢失)
}
//以十进制的形式发送一个16位有符号数
void SCI_SendDec16s(int a)
{
unsigned char b;
if(a&0x8000)//a为负数
{
SCI_SendChar('-');
a = ~a +1; //取绝对值
}
b = (unsigned char)(a/10000);//取万位
b = b + '0';
SCI_SendChar(b);
a = a%10000;
b = (unsigned char)(a/1000);//取千位
b = b + '0';
SCI_SendChar(b);
a = a%1000;
b = (unsigned char)(a/100);//取百位
b = b + '0';
SCI_SendChar(b);
a = a%100;
b = (unsigned char)(a/10);//取十位
b = b + '0';
SCI_SendChar(b);
b = (unsigned char)(a%10);//取个位
b = b + '0';
SCI_SendChar(b);
}
//以十进制的形式发送一个16位无符号数
void SCI_SendDec16u(unsigned int a)
{
unsigned char b;
b = (unsigned char)(a/10000);//取万位
b = b + '0';
SCI_SendChar(b);
a = a%10000;
b = (unsigned char)(a/1000);//取千位
b = b + '0';
SCI_SendChar(b);
a = a%1000;
b = (unsigned char)(a/100);//取百位
b = b + '0';
SCI_SendChar(b);
a = a%100;
b = (unsigned char)(a/10);//取十位
b = b + '0';
SCI_SendChar(b);
b = (unsigned char)(a%10);//取个位
b = b + '0';
SCI_SendChar(b);
}
//接收字符中断服务程序
char data;
#pragma CODE_SEG __NEAR_SEG NON_BANKED
void interrupt 20 SCI0_Interrupt(void)
{
if(SCI0SR1_RDRF == 1)//如果是接收到了字符
{
SCI0DRL;//清除RDRF的标志位
data=SCI0DRL;//读取接收到的字符到data中
}
}