stm32f103c8t6输出spwm代码
时间: 2023-09-12 21:11:55 浏览: 108
以下是一个基于STM32F103C8T6芯片的SPWM输出的代码示例,代码中使用了定时器3和定时器4来生成SPWM波形:
```c
#include "stm32f10x.h"
#define PI 3.1415926
#define PWM_FREQ 1000
#define PWM_PERIOD (72000000 / PWM_FREQ)
void TIM3_PWM_Init(void)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
TIM_TimeBaseStructure.TIM_Period = PWM_PERIOD;
TIM_TimeBaseStructure.TIM_Prescaler = 0;
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM3, &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_OC3Init(TIM3, &TIM_OCInitStructure);
TIM_Cmd(TIM3, ENABLE);
}
void TIM4_PWM_Init(void)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM4, ENABLE);
TIM_TimeBaseStructure.TIM_Period = PWM_PERIOD;
TIM_TimeBaseStructure.TIM_Prescaler = 0;
TIM_TimeBaseStructure.TIM_ClockDivision = TIM_CKD_DIV1;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM4, &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_OC3Init(TIM4, &TIM_OCInitStructure);
TIM_Cmd(TIM4, ENABLE);
}
int main(void)
{
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_AFIO, ENABLE);
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_7 | GPIO_Pin_8;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
TIM3_PWM_Init();
TIM4_PWM_Init();
uint16_t sin_table[PWM_PERIOD];
for (int i = 0; i < PWM_PERIOD; i++) {
sin_table[i] = (sin(2 * PI * i / PWM_PERIOD) + 1) * (PWM_PERIOD / 2);
}
int phase_shift = PWM_PERIOD / 3;
int offset = 0;
while (1) {
for (int i = 0; i < PWM_PERIOD; i++) {
TIM_SetCompare3(TIM3, sin_table[(i + offset) % PWM_PERIOD]);
TIM_SetCompare3(TIM4, sin_table[(i + phase_shift + offset) % PWM_PERIOD]);
for (int j = 0; j < 100; j++);
}
offset++;
if (offset >= PWM_PERIOD) {
offset = 0;
}
}
}
```
代码中使用定时器3和定时器4输出两路SPWM波形,其中`sin_table`数组存储了一个完整的正弦波周期的PWM值,通过改变`offset`变量的值来实现相位移动。需要注意的是,在实际应用中需要根据具体的电机或电器特性调整PWM频率、周期和幅值等参数。
阅读全文