You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
70 lines
1.7 KiB
70 lines
1.7 KiB
/*
|
|
* bsp_adc.c
|
|
*
|
|
* Created on: Feb 21, 2025
|
|
* Author: akeguo
|
|
*/
|
|
|
|
#include "bsp_adc.h"
|
|
#include "adc.h"
|
|
#include "stm32h7xx_hal_adc.h"
|
|
|
|
#include <math.h>
|
|
|
|
// 硬件相关参数配置
|
|
#define ADC_MAX_VALUE 0xffff // 16位ADC最大值,若为10位ADC改为1023
|
|
#define VREF 3.3f // ADC参考电压
|
|
|
|
// 热敏电阻参数 (需根据实际型号确认)
|
|
#define R_REF 10000.0f // 分压电阻阻值(与热敏电阻串联)
|
|
#define B_VALUE 3380.0f // B常数 (需确认具体型号参数)
|
|
#define R0 10000.0f // 25°C时的标称阻值
|
|
#define T0 298.15f // 25°C对应的开尔文温度(25 + 273.15)
|
|
uint32_t adc_value;
|
|
|
|
|
|
int32_t read_temperature()
|
|
{
|
|
|
|
HAL_ADC_Start(&hadc2); //开启ADC1
|
|
|
|
if (HAL_ADC_PollForConversion(&hadc2, 100) == HAL_OK)
|
|
{
|
|
//16 bit resolution
|
|
adc_value = HAL_ADC_GetValue(&hadc2);
|
|
|
|
HAL_ADC_Stop(&hadc2);
|
|
// 1. 计算热敏电阻两端电压
|
|
float voltage = (adc_value / (float) ADC_MAX_VALUE) * VREF;
|
|
|
|
// 2. 计算热敏电阻阻值(分压电路公式)
|
|
float ntc_resistance = (voltage * R_REF) / (VREF - voltage);
|
|
//float ntc_resistance = (voltage * R_REF) / (VREF);
|
|
// 3. 使用Steinhart-Hart方程计算温度
|
|
float steinhart;
|
|
steinhart = ntc_resistance / R0; // (R/R0)
|
|
steinhart = log(steinhart); // ln(R/R0)
|
|
steinhart /= B_VALUE; // 1/B * ln(R/R0)
|
|
steinhart += 1.0 / T0; // + (1/T0)
|
|
steinhart = 1.0 / steinhart; // 取倒数得到开尔文温度
|
|
|
|
|
|
// 4. 转换为摄氏度并返回
|
|
return (int32_t)((steinhart - 273.15)*100);
|
|
}
|
|
else
|
|
{
|
|
adc_value = 0;
|
|
HAL_ADC_Stop(&hadc2);
|
|
return 0;
|
|
}
|
|
|
|
}
|
|
|
|
int32_t temperature;
|
|
|
|
double GetTempature()
|
|
{
|
|
|
|
//return 0;
|
|
}
|
|
|