文章目录
工程结构:
原理图:
main.c
/**
* Interrupt Registers Definition
*/
sfr IE = 0xA8; /* Interrupt Enable Register */
sfr IE2 = 0xAF;
/**
* Interrupt Registers Bits Definition
*/
/** IE */
#define GLOBAL_IE_EA (0x80)
/** IE2 */
#define T2_IE2_ET2 (0x04)
/**
* Port Switch Register
*/
sfr P_SW2 = 0xBA;
/**
* Port Switch Register Bits Definition
*/
#define P_SW2_EAXFR (0x80)
/**
* Timer 2 Registers Definition
*/
#define TM2PS (*(unsigned char volatile xdata *)0xFEA2) /* Timer 2 Prescaler Register */
sfr T2L = 0xD7; /* Timer 2 Counter Low Register */
sfr T2H = 0xD6; /* Timer 2 Counter High Register */
sfr AUXR = 0x8E; /* Auxiliary Register */
/**
* Timer 2 Registers Bits Definition
*/
/** AUXR */
#define T2_AUXR_T2R (0x10) /* Timer 1 - Run Control */
#define T2_AUXR_T2_CT (0x08) /* Timer 1 - Counter or Timer Selection */
#define T2_AUXR_T2x12 (0x04) /* Timer 1 - Clock Divider Control */
/**
* Port 1 Registers Definition
*/
sfr P1 = 0x90; /* Port 1 Register */
sfr P1M1 = 0x91; /* Port 1 Configuration Register 1 */
sfr P1M0 = 0x92; /* Port 1 Configuration Register 0 */
/**
* Port 1 Registers Bits Definition
*/
#define P12M1 (0x04) /* P1.2 - Mode Selection Bit 1 */
#define P12M0 (0x04) /* P1.2 - Mode Selection Bit 0 */
#define enableInterrupts() IE |= GLOBAL_IE_EA
#define disableInterrupts() IE &= ~GLOBAL_IE_EA
#define INTERNAL_RC_OSCILLATOR_FREQUENCY_11059200HZ (11059200L) /* 11.0592 MHz */
#define INTERNAL_RC_OSCILLATOR_FREQUENCY_12000000HZ (12000000L) /* 12.0000 MHz */
#define SYSTEM_CLOCK (INTERNAL_RC_OSCILLATOR_FREQUENCY_12000000HZ)
sbit LED = P1^2; /* LED Control Bit. 0: On, 1: Off */
/**
* Timer 2 - 16-Bit Auto Reload
*/
void main() {
unsigned int period = 2000; // 定时器计数周期,溢出频率 = 1 / 定时器计数周期
unsigned char divider = 1; // 时钟分频器
AUXR &= ~T2_AUXR_T2_CT; // T2 作为定时器(对内部系统时钟进行计数)
AUXR |= T2_AUXR_T2x12; // 不分频 T2 的时钟
divider = ((AUXR & T2_AUXR_T2x12) == T2_AUXR_T2x12) ? 1 : 12;
T2H = (65536 - SYSTEM_CLOCK / divider / period) >> 8;
T2L = (65536 - SYSTEM_CLOCK / divider / period);
P_SW2 |= P_SW2_EAXFR; // 允许访问位于扩展 RAM 区的特殊功能寄存器
TM2PS = 0; // 对 T2 的时钟进行 1 分频。分频公式:系统时钟 ÷ (TM2PS + 1)
P_SW2 &= ~P_SW2_EAXFR; // 禁止访问位于扩展 RAM 区的特殊功能寄存器
IE2 |= T2_IE2_ET2; // 允许 T2 在计数溢出之后请求中断
AUXR |= T2_AUXR_T2R; // 允许 T2 开始计数
P1M1 &= ~P12M1;
P1M0 |= P12M0;
enableInterrupts();
while(1) {}
}
void timer2InterruptService() interrupt 12 {
LED = !LED;
}
STC-ISP 的下载选项: