读取 MCU ID,然后通过串口发送
原理图
示例
main.c 文件:
#include <reg51.h>
#ifndef SYSTEM_CLOCK
#define SYSTEM_CLOCK (1000000 * 12)
#endif
typedef enum {
FALSE = 0, TRUE = !FALSE
} boolean;
#define PCON_SMOD 0x80
#define PCON_SMOD0 0x40
sfr AUXR = 0x8E;
#define AUXR_BRTR 0x10
#define AUXR_BRTx12 0x04
#define AUXR_S1BRS 0x01
sfr BRT = 0x9C;
sfr AUXR1 = 0xA2;
#define AUXR1_UART_P1 0x80
#define UART1_BAUD_RATE 9600
#define MCU_ID_START_ADDRESS (0xF1)
#define MCU_ID_END_ADDRESS (0xF7)
#define MCU_ID_ADDRESS_LENGTH (MCU_ID_END_ADDRESS - MCU_ID_START_ADDRESS + 1)
void uartInit(unsigned int baudRate);
boolean getMcuId(unsigned char mcuId[7]);
void main() {
uartInit(UART1_BAUD_RATE);
EA = 1;
{
unsigned char mcuId[7];
if (getMcuId(mcuId) == TRUE) {
unsigned char i = 0;
for (i = 0; i < MCU_ID_ADDRESS_LENGTH; i++) {
SBUF = mcuId[i];
while (!TI);
}
}
}
while(1) {}
}
void uartInterruptService() interrupt 4 {
unsigned char buffer = 0x00;
if (RI) {
RI = 0;
buffer = SBUF;
SBUF = buffer;
}
if (TI) {
TI = 0;
}
}
void uartInit(unsigned int baudRate) {
PCON &= ~PCON_SMOD;
PCON &= ~PCON_SMOD0;
SM0 = 0;
SM1 = 1;
REN = 1;
TI = 0;
RI = 0;
if((PCON & PCON_SMOD) == PCON_SMOD) {
BRT = 256 - (SYSTEM_CLOCK / 16 / baudRate);
} else {
BRT = 256 - (SYSTEM_CLOCK / 32 / baudRate);
}
AUXR |= AUXR_S1BRS;
AUXR |= AUXR_BRTx12;
AUXR |= AUXR_BRTR;
ES = 1;
}
boolean getMcuId(unsigned char mcuId[7]) {
unsigned char idata *mcuIdAddress = MCU_ID_START_ADDRESS;
unsigned char i;
for (i = 0; i < MCU_ID_ADDRESS_LENGTH; i++) {
mcuId[i] = *mcuIdAddress;
mcuIdAddress++;
}
return i == MCU_ID_ADDRESS_LENGTH ? TRUE : FALSE;
}
打开连接单片机的串口,重新给单片机上电或是复位单片机,可见单片机将 MCU ID 发给串口:
参考
宏晶科技 STC - STC11 & 10xx 系列单片机器件手册
|