看论坛上有人用EG8010和TDS2285做逆变器,小弟现在再调试一款STM8S003的小板,感觉资源也够,只要有PWM和ADC应该就差不多,试着想自己编一个程序试试
该程序主要完成STM TIM1的1,2通道互补输出,20K的载波,50hz的基波
#include "IOSTM8S103K3.h" #include "math.h" #includeunsigned char pwm_duty[100]; #define LED PC_ODR_ODR4 #define IN PD_IDR_IDR3 unsigned char t,v; unsigned char a,i,j,count; unsigned long k,sum,l; void math(void) { unsigned char i; for(i=0; i<100; i++) { //if(j<= 50) pwm_duty[i]=(unsigned char)(0+(float)254*sin(2*3.1415926*(float)i*0.2/(float)20)); //if(j> 50) pwm_duty[i]=(unsigned char)(254-(float)254*sin(2*3.1415926*(float)i*0.2/(float)20)); pwm_duty[i]=(unsigned char)(127+(float)127*sin(2*3.1415926*(float)i*0.2/(float)20)); } } void delay_ms(unsigned int ms) { unsigned char i; while(ms!=0) { for(i=0;i<250;i++) {} for(i=0;i<75;i++) {} ms--; } } 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=0x04;//分频值128 asm("rim");//开全局中断,延时16.32ms } #pragma vector=TIM4_OVR_UIF_vector//0x19 __interrupt void TIM4_OVR_UIF_IRQHandler(void)//对应IAP的中断地址:0x8060 { //asm("JP 0x9060\n"); TIM4_SR=0x00; if(k>= 100) k=0; TIM1_CCR1L = pwm_duty[k]; TIM1_CCR2L = pwm_duty[k]; k++; //return; } void TIM1_CH1_PWM_INIT(void) { CLK_PCKENR1|=0x80;//开启定时器1外设时钟 TIM1_EGR=0x01;//重新初始化TIM1 TIM1_EGR|=0x20;//重新初始化TIM1 TIM1_ARRH=0x00;//设定重装载值 TIM1_ARRL=255; TIM1_PSCRH=0;//预分频 TIM1_PSCRL=0x04; TIM1_CR1=0;//边沿对齐,向上计数 TIM1_CCER1=0x55;//高电平有效 TIM1_CCMR1=0x60;//PWM模式1 TIM1_CCMR2=0x60;//PWM模式1 TIM1_DTR=0x04; TIM1_CCR1H=0;//占空比 TIM1_CCR1L=254; TIM1_CCR2H=0;//占空比 TIM1_CCR2L=254; TIM1_CR1|=0x01;//向上计数,无缓存,使能 TIM1_BKR=0x80;//开启刹车 } void TIM2_CH1_PWM_INIT(void) { TIM2_CCMR1 = TIM2_CCMR1 | 0x70;// Output mode PWM2. TIM2_CCMR3 = TIM2_CCMR3 | 0x70;// Output mode PWM2. // 通道2 被设置成比较输出方式 // OC2M = 111,为PWM 模式2, // 向上计数时,若计数器小于比较值,为无效电平 // 即当计数器在0 到比较值时,输出为1,否则为0 TIM2_CCER1 = TIM2_CCER1 | 0x03;// CC polarity low,enable PWM output */ TIM2_CCER2 = TIM2_CCER2 | 0x03; // CC2P = 1,低电平为有效电平 // CC2E = 1,开启输出引脚 //初始化自动装载寄存器,决定PWM 方波的频率,Fpwm=4000000/256=15625HZ TIM2_ARRH = 0; TIM2_ARRL = 0xFF; //初始化比较寄存器,决定PWM 方波的占空比 TIM2_CCR1H = 0; TIM2_CCR1L = 0; TIM2_CCR3H = 0; TIM2_CCR3L = 0; // 初始化时钟分频器为2,即计数器的时钟频率为Fmaster=8MHZ TIM2_PSCR = 1; // 启动计数 TIM2_CR1 = TIM2_CR1 | 0x01; } void main( void ) { CLK_CKDIVR=0x00; math(); PA_DDR|=0x08; PA_CR1|=0x08; PA_CR2|=0x00; PA_ODR|=0x08; PC_DDR|=0x58; PC_CR1|=0x58; PC_CR2|=0x00; // PC_ODR|=0x58; PD_DDR|=0x10; PD_CR1|=0x10; PD_CR2|=0x00; Init_Timer4(); TIM1_CH1_PWM_INIT(); // TIM2_CH1_PWM_INIT(); TIM2_CCR1L = 128; TIM2_CCR3L = 0; TIM1_CCR1L=128; TIM1_CCR2L=128; while(1) { } }