24.2.1 使能高级PWM的高速模式(异步模式)
//测试工作频率为24MHz #include "stc8h.h" #include "intrins.h" #define FOSC 24000000UL #define HSCK_MCLK 0 #define HSCK_PLL 1 #define HSCK_SEL HSCK_PLL #define PLL_96M 0 #define PLL_144M 1 #define PLL_SEL PLL_144M #define CKMS 0x80 #define HSIOCK 0x40 #define MCK2SEL_MSK 0x0c #define MCK2SEL_SEL1 0x00 #define MCK2SEL_PLLD2 0x04 #define MCK2SEL_PLLD4 0x08 #define MCKSEL_MSK 0x03 #define MCKSEL_HIRC 0x00 #define MCKSEL_XOSC 0x01 #define MCKSEL_X32K 0x02 #define MCKSEL_IRC32K 0x03 #define ENCKM 0x80 #define PCKI_MSK 0x60 #define PCKI_D1 0x00 #define PCKI_D2 0x20 #define PCKI_D3 0x40 #define PCKI_D4 0x60 void delay() { int i; for (i=0; i<100; i++); } char ReadPWMA(char addr) { chardat; while(HSPWMA_ADR & 0x80); //等待前一个异步读写完成 HSPWMA_ADR= addr | 0x80; //设置间接访问地址,只需要设置原XFR地址的低7位 //HSPWMA_ADR寄存器的最高位写1,表示读数据 while(HSPWMA_ADR & 0x80); //等待当前异步读取完成 dat = HSPWMA_DAT; //读取异步数据 returndat; } void WritePWMA(char addr, chardat) { while(HSPWMA_ADR & 0x80); //等待前一个异步读写完成 HSPWMA_DAT= dat; //准备需要写入的数据 HSPWMA_ADR= addr & 0x7f; //设置间接访问地址,只需要设置原XFR地址的低7位 //HSPWMA_ADR寄存器的最高位写0,表示写数据 } void main() { P_SW2|= 0x80; //使能访问XFR //选择PLL输出时钟 #if (PLL_SEL == PLL_96M) CLKSEL&= ~CKMS; //选择PLL的96M作为PLL的输出时钟 #elif (PLL_SEL == PLL_144M) CLKSEL|= CKMS; //选择PLL的144M作为PLL的输出时钟 #else CLKSEL&= ~CKMS; //默认选择PLL的96M作为PLL的输出时钟 #endif //选择PLL输入时钟分频,保证输入时钟为12M PLLCR&= ~PCKI_MSK; #if (FOSC == 12000000UL) PLLCR|= PCKI_D1; //PLL输入时钟1分频 #elif (FOSC == 24000000UL) PLLCR|= PCKI_D2; //PLL输入时钟2分频 #elif (FOSC == 36000000UL) PLLCR|= PCKI_D3; //PLL输入时钟3分频 #elif (FOSC == 48000000UL) PLLCR|= PCKI_D4; //PLL输入时钟4分频 #else PLLCR|= PCKI_D1; //默认PLL输入时钟1分频 #endif //启动PLL PLLCR|= ENCKM; //使能PLL倍频 delay(); //等待PLL锁频 //选择HSPWM/HSSPI时钟 #if (HSCK_SEL == HSCK_MCLK) CLKSEL&= ~HSIOCK; //HSPWM/HSSPI选择主时钟为时钟源 #elif (HSCK_SEL == HSCK_PLL) CLKSEL|= HSIOCK; //HSPWM/HSSPI选择PLL输出时钟为时钟源 #else CLKSEL&= ~HSIOCK; //默认HSPWM/HSSPI选择主时钟为时钟源 #endif HSCLKDIV= 0; //HSPWM/HSSPI时钟源不分频 HSPWMA_CFG= 0x03; //使能PWMA相关寄存器异步访问功能 //通过异步方式设置PWMA的相关寄存器 WritePWMA((char)&PWMA_CCER1,0x00); WritePWMA((char)&PWMA_CCMR1,0x00); //CC1为输出模式 WritePWMA((char)&PWMA_CCMR1,0x60); //OC1REF输出PWM1(CNT<CCR时输出有效电平1) WritePWMA((char)&PWMA_CCER1,0x05); //使能CC1/CC1N上的输出功能 WritePWMA((char)&PWMA_ENO,0x03); //使能PWM信号输出到端口 WritePWMA((char)&PWMA_BKR,0x80); //使能主输出 WritePWMA((char)&PWMA_CCR1H,200 >> 8); //设置输出PWM的占空比 WritePWMA((char)&PWMA_CCR1L,200); WritePWMA((char)&PWMA_ARRH,1000 >> 8); //设置输出PWM的周期 WritePWMA((char)&PWMA_ARRL,1000); WritePWMA((char)&PWMA_DTR,10); //设置互补对称输出PWM的死区 WritePWMA((char)&PWMA_CR1,0x01); //开始PWM计数 P2M0= 0; P2M1= 0; P3M0= 0; P3M1= 0; P2= ReadPWMA((char)&PWMA_ARRH); //异步方式读取寄存器 P3= ReadPWMA((char)&PWMA_ARRL); while(1); }
|