STM32F1 thd计算程序
时间: 2023-10-13 15:07:54 浏览: 91
以下是一个简单的STM32F1 THD计算程序:
```c
#include "stm32f10x.h"
#define SAMPLES 256
#define PI 3.14159265359
uint16_t adc_buffer[SAMPLES];
float thd;
void GPIO_Configuration(void);
void ADC_Configuration(void);
void TIM_Configuration(void);
int main(void) {
GPIO_Configuration();
ADC_Configuration();
TIM_Configuration();
while (1) {
}
}
void GPIO_Configuration(void) {
// Configure PC0 as analog input
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AIN;
GPIO_Init(GPIOC, &GPIO_InitStructure);
}
void ADC_Configuration(void) {
// Configure ADC1
ADC_InitTypeDef ADC_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC1, ENABLE);
ADC_InitStructure.ADC_Mode = ADC_Mode_Independent;
ADC_InitStructure.ADC_ScanConvMode = DISABLE;
ADC_InitStructure.ADC_ContinuousConvMode = ENABLE;
ADC_InitStructure.ADC_ExternalTrigConv = ADC_ExternalTrigConv_None;
ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right;
ADC_InitStructure.ADC_NbrOfChannel = 1;
ADC_Init(ADC1, &ADC_InitStructure);
// Configure ADC1 channel 10 (PC0)
ADC_RegularChannelConfig(ADC1, ADC_Channel_10, 1, ADC_SampleTime_55Cycles5);
// Enable ADC1
ADC_Cmd(ADC1, ENABLE);
// Start ADC1
ADC_SoftwareStartConvCmd(ADC1, ENABLE);
}
void TIM_Configuration(void) {
// Configure TIM2 for 1ms timer interrupt
TIM_TimeBaseInitTypeDef TIM_TimeBaseStructure;
RCC_APB1PeriphClockCmd(RCC_APB1Periph_TIM2, ENABLE);
TIM_TimeBaseStructure.TIM_Period = 7199;
TIM_TimeBaseStructure.TIM_Prescaler = 999;
TIM_TimeBaseStructure.TIM_ClockDivision = 0;
TIM_TimeBaseStructure.TIM_CounterMode = TIM_CounterMode_Up;
TIM_TimeBaseInit(TIM2, &TIM_TimeBaseStructure);
// Enable TIM2 interrupt
NVIC_InitTypeDef NVIC_InitStructure;
NVIC_InitStructure.NVIC_IRQChannel = TIM2_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
TIM_ITConfig(TIM2, TIM_IT_Update, ENABLE);
TIM_Cmd(TIM2, ENABLE);
}
void TIM2_IRQHandler(void) {
if (TIM_GetITStatus(TIM2, TIM_IT_Update) != RESET) {
// Read ADC buffer
for (int i = 0; i < SAMPLES; i++) {
adc_buffer[i] = ADC_GetConversionValue(ADC1);
}
// Calculate THD
float sum = 0;
float fundamental = 0;
for (int i = 0; i < SAMPLES; i++) {
float value = (float)adc_buffer[i] / 4096.0 * 3.3;
sum += value * value;
if (i == 0) {
fundamental = value;
}
}
sum -= fundamental * fundamental;
thd = sqrtf(sum) / fundamental;
TIM_ClearITPendingBit(TIM2, TIM_IT_Update);
}
}
```
该程序配置了STM32F1的ADC和定时器,通过读取ADC缓冲区中的采样数据来计算THD。计算THD的过程是使用RMS计算基波和总谐波的平方和,然后除以基波的幅度,最后开平方根。在本例中,使用的是256个采样点,采样时间为55个时钟周期,采样频率为1.1kHz。
阅读全文