28335输出spwm
时间: 2023-11-12 18:04:03 浏览: 78
SPWM(正弦波脉宽调制)是一种用于控制交流电机的技术,它可以产生接近于正弦波的输出信号。下面是一个基于STM32的SPWM输出程序示例:
```c
#include "stm32f10x.h"
#define PI 3.1415926
#define SAMPLE_RATE 1000 //采样率
#define PWM_FREQ 50 //PWM频率
#define PWM_PERIOD ((uint16_t)(SystemCoreClock / (SAMPLE_RATE * 2 * PWM_FREQ)))
uint16_t sinTable[360] = {0}; //正弦表
uint16_t dutyTable[360] = {0}; //占空比表
void TIM3_Configuration(void)
{
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
TIM_OCInitTypeDef TIM_OCInitStructure;
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM3, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6 | GPIO_Pin_7 | 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);
TIM_TimeBaseStructure.TIM_Period = PWM_PERIOD - 1;
TIM_TimeBaseStructure.TIM_Prescaler = 0;
TIM_TimeBaseStructure.TIM_ClockDivision = 0;
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_OC1Init(TIM3, &TIM_OCInitStructure);
TIM_OC2Init(TIM3, &TIM_OCInitStructure);
TIM_OC3Init(TIM3, &TIM_OCInitStructure);
TIM_OC4Init(TIM3, &TIM_OCInitStructure);
TIM_Cmd(TIM3, ENABLE);
}
void generateSinTable(void)
{
uint16_t i;
for(i = 0; i < 360; i++)
{
sinTable[i] = (uint16_t)(PWM_PERIOD / 2 * (1 + sin(i * PI / 180)));
}
}
void generateDutyTable(void)
{
uint16_t i;
for(i = 0; i < 360; i++)
{
dutyTable[i] = (uint16_t)(PWM_PERIOD * i / 360);
}
}
int main(void)
{
uint16_t sinIndex = 0;
uint16_t dutyIndex = 0;
generateSinTable();
generateDutyTable();
TIM3_Configuration();
while(1)
{
TIM_SetCompare1(TIM3, dutyTable[dutyIndex]);
TIM_SetCompare2(TIM3, dutyTable[dutyIndex]);
TIM_SetCompare3(TIM3, dutyTable[dutyIndex]);
TIM_SetCompare4(TIM3, sinTable[sinIndex]);
sinIndex++;
if(sinIndex >= 360)
{
sinIndex = 0;
dutyIndex++;
if(dutyIndex >= 360)
{
dutyIndex = 0;
}
}
delay_us(1000000 / SAMPLE_RATE);
}
}
void delay_us(uint32_t nTime)
{
uint32_t i;
SysTick->LOAD = nTime * 9;
SysTick->VAL = 0;
SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk | SysTick_CTRL_ENABLE_Msk;
for(i = 0; i < nTime; i++)
{
while(!(SysTick->CTRL & SysTick_CTRL_COUNTFLAG_Msk));
}
SysTick->CTRL = 0;
}
```
这个程序使用TIM3输出4路PWM信号,其中3路占空比相同,1路输出正弦波。每次更新占空比和正弦波的值时,通过增加索引值来访问预先生成的占空比表和正弦表。程序使用SysTick延时函数来控制采样率。
阅读全文