STC8H1K08 - Timer 2 - 16-Bit Auto Reload

文章目录


工程结构:

在这里插入图片描述

原理图:

在这里插入图片描述

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 的下载选项:

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值