stm32正弦波数据产生函数
时间: 2024-06-09 15:07:49 浏览: 69
STM32ZET6输出正弦波sin
在STM32中产生正弦波可以使用DAC或者PWM输出模式,下面给出两种实现方式:
## 使用DAC
1. 配置DAC
```c
DAC_HandleTypeDef hdac;
void MX_DAC_Init(void)
{
DAC_ChannelConfTypeDef sConfig = {0};
hdac.Instance = DAC1;
if (HAL_DAC_Init(&hdac) != HAL_OK)
{
Error_Handler();
}
sConfig.DAC_Trigger = DAC_TRIGGER_NONE;
sConfig.DAC_OutputBuffer = DAC_OUTPUTBUFFER_DISABLE;
if (HAL_DAC_ConfigChannel(&hdac, &sConfig, DAC_CHANNEL_1) != HAL_OK)
{
Error_Handler();
}
}
```
2. 产生正弦波数据
```c
#define SAMPLE_NUM 100
#define PI 3.1415926f
uint16_t sineWave[SAMPLE_NUM];
void createSinWave(void)
{
for(uint8_t i=0;i<SAMPLE_NUM;i++)
{
sineWave[i]=(uint16_t)(2048.0f*(1.0f+sinf(2.0f*PI*i/SAMPLE_NUM)));
}
}
```
3. 启动DAC,并输出正弦波数据
```c
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
if (htim->Instance == TIM6)
{
HAL_DAC_Start(&hdac, DAC_CHANNEL_1);
HAL_DAC_SetValue(&hdac, DAC_CHANNEL_1, DAC_ALIGN_12B_R, sineWave[counter]);
counter++;
if (counter >= SAMPLE_NUM) counter = 0;
}
}
```
## 使用PWM
1. 配置PWM
```c
TIM_HandleTypeDef htim2;
void MX_TIM2_Init(void)
{
TIM_MasterConfigTypeDef sMasterConfig = {0};
TIM_OC_InitTypeDef sConfigOC = {0};
htim2.Instance = TIM2;
htim2.Init.Prescaler = 0;
htim2.Init.CounterMode = TIM_COUNTERMODE_UP;
htim2.Init.Period = 799;
htim2.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1;
if (HAL_TIM_PWM_Init(&htim2) != HAL_OK)
{
Error_Handler();
}
sMasterConfig.MasterOutputTrigger = TIM_TRGO_RESET;
sMasterConfig.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE;
if (HAL_TIMEx_MasterConfigSynchronization(&htim2, &sMasterConfig) != HAL_OK)
{
Error_Handler();
}
sConfigOC.OCMode = TIM_OCMODE_PWM1;
sConfigOC.Pulse = 399;
sConfigOC.OCPolarity = TIM_OCPOLARITY_HIGH;
sConfigOC.OCFastMode = TIM_OCFAST_DISABLE;
if (HAL_TIM_PWM_ConfigChannel(&htim2, &sConfigOC, TIM_CHANNEL_1) != HAL_OK)
{
Error_Handler();
}
HAL_TIM_MspPostInit(&htim2);
}
```
2. 产生正弦波数据
```c
#define SAMPLE_NUM 100
#define PI 3.1415926f
uint16_t sineWave[SAMPLE_NUM];
void createSinWave(void)
{
for(uint8_t i=0;i<SAMPLE_NUM;i++)
{
sineWave[i]=(uint16_t)(399.0f*(1.0f+sinf(2.0f*PI*i/SAMPLE_NUM)));
}
}
```
3. 启动PWM,并输出正弦波数据
```c
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
if (htim->Instance == TIM6)
{
HAL_TIM_PWM_Start(&htim2, TIM_CHANNEL_1);
__HAL_TIM_SET_COMPARE(&htim2, TIM_CHANNEL_1, sineWave[counter]);
counter++;
if (counter >= SAMPLE_NUM) counter = 0;
}
}
```
阅读全文