STC89C52单片机输出两路PWM控制DC-AC半桥电路程序
时间: 2023-05-27 14:04:52 浏览: 111
由于缺乏具体硬件电路信息,下面提供的是STM32单片机输出两路PWM控制DC-AC半桥电路的示例程序,供参考。
#include "stm32f10x.h"
#define PWM_FREQUENCY 100 //设置PWM频率,单位为Hz
#define PWM_PERIOD (84000000/PWM_FREQUENCY/2) //PSC=2,如需设定不同频率可更改此值
int main(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE); //使能GPIOA口的时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_TIM1, ENABLE); //使能TIM1的时钟
//PA8-9使能PWM1输出管脚
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_8 | GPIO_Pin_9;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
//PWM1输出频率为20KHz,占空比从0-100%
TIM_TimeBaseStructure.TIM_Period = PWM_PERIOD-1;
TIM_TimeBaseStructure.TIM_Prescaler = 2-1;
TIM_TimeBaseStructure.TIM_ClockDivision = 0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM1, &TIM_TimeBaseStructure);
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_Pulse = 0;
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OC1Init(TIM1, &TIM_OCInitStructure);
TIM_OC1PreloadConfig(TIM1, TIM_OCPreload_Enable);
TIM_OCInitStructure.TIM_OCMode = TIM_OCMode_PWM1;
TIM_OCInitStructure.TIM_OutputState = TIM_OutputState_Enable;
TIM_OCInitStructure.TIM_Pulse = 0;
TIM_OCInitStructure.TIM_OCPolarity = TIM_OCPolarity_High;
TIM_OC2Init(TIM1, &TIM_OCInitStructure);
TIM_OC2PreloadConfig(TIM1, TIM_OCPreload_Enable);
TIM_Cmd(TIM1, ENABLE);
while (1)
{
//占空比从10%-90%之间变化
for (u16 duty = 10; duty < 90; duty ++)
{
TIM_SetCompare1(TIM1, PWM_PERIOD/100*duty); //设置PWM1的占空比
TIM_SetCompare2(TIM1, PWM_PERIOD/100*(100-duty)); //设置PWM2的占空比
Delay_ms(500);
}
//逆向占空比变化
for (u16 duty = 90; duty > 10; duty --)
{
TIM_SetCompare1(TIM1, PWM_PERIOD/100*duty);
TIM_SetCompare2(TIM1, PWM_PERIOD/100*(100-duty));
Delay_ms(500);
}
}
}
void Delay_ms(u16 n)
{
u32 i = 0;
while (n--)
{
i = 10000;
while (i--);
}
}
阅读全文