写一个通过stm32f103zet6、20A量程的ACS712使用ADC2来测量电流的MDK代码
时间: 2024-06-06 16:07:51 浏览: 146
#include "stm32f10x.h"
int main()
{
// 初始化ADC2
RCC_APB2PeriphClockCmd(RCC_APB2Periph_ADC2, ENABLE);
ADC_InitTypeDef ADC_InitStructure;
ADC_InitStructure.ADC_Mode = ADC_Mode_Independent;
ADC_InitStructure.ADC_ScanConvMode = DISABLE;
ADC_InitStructure.ADC_ContinuousConvMode = DISABLE;
ADC_InitStructure.ADC_ExternalTrigConv = ADC_ExternalTrigConv_None;
ADC_InitStructure.ADC_DataAlign = ADC_DataAlign_Right;
ADC_InitStructure.ADC_NbrOfChannel = 1;
ADC_Init(ADC2, &ADC_InitStructure);
ADC_Cmd(ADC2, ENABLE);
// 初始化GPIO
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_0;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AIN;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStructure);
// 循环读取ADC值
while(1)
{
ADC_RegularChannelConfig(ADC2, ADC_Channel_0, 1, ADC_SampleTime_239Cycles5);
ADC_SoftwareStartConvCmd(ADC2, ENABLE);
while(!ADC_GetFlagStatus(ADC2, ADC_FLAG_EOC));
uint16_t adc_value = ADC_GetConversionValue(ADC2);
// 计算电流值
float voltage = adc_value * 3.3 / 4096;
float current = (voltage - 1.65) / 0.185;
// 处理电流值
if(current < 0) current = 0;
if(current > 20) current = 20;
// 输出电流值
printf("Current: %.2fA\n", current);
}
}
阅读全文