最近开始学习使用STC单片机来做项目,支持国产芯片,STC单片机的标准库大多已寄存器操作为主,入门成本比较高,需要加强这部分基础知识
1. 定义特殊寄存器
sfr IE = 0xA8;
sfr IP = 0xB8;
sfr SCON = 0x98; // 串口1控制寄存器
sfr SBUF = 0x99; // 串口1发送缓冲
使用sfr关键字定义特殊寄存器SCON 串口1控制寄存器
scon有8个BIt,是一个可寻址的特殊寄存器, 这里可以使用sbit来定义 0x98地址处的8位别名
0x98 ^ (bit_address)
/* SCON */
sbit SM0 = 0x9F;
sbit SM1 = 0x9E;
sbit SM2 = 0x9D;
sbit REN = 0x9C;
sbit TB8 = 0x9B;
sbit RB8 = 0x9A;
sbit TI = 0x99; // 发送忙标识
sbit RI = 0x98; // 接收忙标识
2. 操作串口发送数据
void UartIsr() interrupt 4
{
if (TI)
{
TI = 0;
busy = 0;
}
if (RI)
{
RI = 0;
}
}
void UartInit()
{
SCON = 0x50;
TMOD = 0x00;
TL1 = BRT;
TH1 = BRT >> 8;
TR1 = 1;
AUXR = 0x40;
busy = 0;
}
void UartSend(char dat)
{
while (busy);
busy = 1;
SBUF = dat;
}
TI标识的是串口发送状态,发送结束以后由单片机自动置1,然后触发中断4,检查busy状态即可发送下一个字符,SBUF则是串口1的发送数据缓冲
3. 哪些是Bit-Addressable寄存器
想要可以使用sbit,必须是可以被0或者8整除的,这样我们可以使用相应的算法反推寄存器地址,和要取的位数
比如前面的TI 定义为 0x99
寄存器地址为: 0x99 - 0x99%8 = 0x98
位:0x99 % 8 = 1
汇编以后的代码
25: void UartIsr() interrupt 4
26: {
27: if (TI)
C:0x00A9 309904 JNB TI(0x98.1),C:00B0
28: {
29: TI = 0;
C:0x00AC C299 CLR TI(0x98.1)
30: busy = 0;
C:0x00AE C200 CLR busy(0x20.0)
31: }
32: if (RI)
C:0x00B0 309802 JNB RI(0x98.0),C:00B5
33: {
34: RI = 0;
C:0x00B3 C298 CLR RI(0x98.0)
35: }
36: }
在熟悉了sfr bit关键字以后,STC的代码基本就能理解了,不过对于记忆力难度很高,各种名称标识不如STM明了,还需要对着PDF文档一页页翻,查每一个BIt的具体含义,考虑到创始人的极客个性,显的B格是比STM32高了那么一点点吧
狗头
- Not all SFRs are bit-addressable. Only those SFRs whose address is evenly divisible by 8 are bit-addressable. The lower nibble of the SFR's address must be 0 or 8. For example, SFRs at 0xA8 and 0xD0 are bit-addressable, whereas SFRs at 0xC7 and 0xEB are not. To calculate an SFR bit address, add the bit position to the SFR byte address. So, to access bit 6 in the SFR at 0xC8, the SFR bit address would be 0xCE (0xC8 + 6).
- Special function bits represent an independent declaration class that may not be interchangeable with other bit declarations or bit fields.
- The sbit data type declaration may be used to access individual bits of variables declared with the bdata memory type specifier. Refer to Bit-addressable Objects for more information.
- sbit variables may not be declared inside a function. They must be declared outside of the function body.
参考