今天用STM8s试了下调制SPWM,查表法做的,定时器1通道2引脚输出SPWM,又通过一个LC滤波,就看到了下面的正弦波
#include "IOSTM8S103K3.h" #include "math.h" #include#define LED PC_ODR_ODR2 unsigned int pwm_duty[100]; unsigned char j=0; /* Phase difference */ unsigned char cnt_pwm=0; void math(void) { unsigned char i; for(i=0; i<100; i++) { pwm_duty[i]=(unsigned int)(127+(float)127*sin(2*3.1415926*(float)i*0.2/(float)20)); } } void delay_us(unsigned int us) { unsigned char j; while(us!=0) { for(j=0;j<250;j++) {} us--; } } void Init_Timer4(void) { asm("sim"); TIM4_CR1=0x01;//使能计数器 TIM4_IER=0x01;//更新中断使能 TIM4_EGR=0x01; TIM4_CNTR=199;//计数器值 TIM4_ARR=199;//自动重装的值 TIM4_PSCR=0x02;//分频值128 asm("rim");//开全局中断,延时16.32ms } #pragma vector=TIM4_OVR_UIF_vector//0x19 __interrupt void TIM4_OVR_UIF_IRQHandler(void)//对应IAP的中断地址:0x8060 { TIM4_SR=0x00; cnt_pwm++; if (cnt_pwm>3) { cnt_pwm=0; /* Sin wave CC1 PB0*/ if(j>= 100) j=0; TIM1_CCR2H = (unsigned char)(pwm_duty[j]>>8); TIM1_CCR2L = (unsigned char)(pwm_duty[j]&0x00ff); j++; } } void TIM1_CH2_PWM_INIT(void) { CLK_PCKENR1|=0x80;//开启定时器1外设时钟 TIM1_EGR=0x01;//重新初始化TIM1 TIM1_EGR|=0x60;//重新初始化TIM1 TIM1_ARRH=0x00;//设定重装载值 TIM1_ARRL=255; TIM1_PSCRH=0;//预分频 TIM1_PSCRL=1; TIM1_CR1=0;//边沿对齐,向上计数 TIM1_CCER1=0x11;//高电平有效 TIM1_CCMR1=0x60;//PWM模式1 TIM1_CCMR2=0x60;//PWM模式1 TIM1_CCR2H=0;//占空比 TIM1_CCR2L=254; TIM1_CCR1H=0;//占空比 TIM1_CCR1L=254; TIM1_CR1|=0x01;//向上计数,无缓存,使能 TIM1_BKR=0x80;//开启刹车 } void main( void ) { /*High speed internal clock prescaler: 1*/ CLK_CKDIVR = 0x00; math(); PC_DDR|=0x04; PC_CR1|=0x04; PC_CR2|=0x00; Init_Timer4(); TIM1_CH2_PWM_INIT(); while(1) { } }