#include <Arduino.h>
// 假设热敏电阻连接在A1引脚
const int thermistorPin = A1;
// 热敏电阻的β系数,这个值应该与您的热敏电阻相匹配
const float B = 3950;
// 25°C时的电阻值(欧姆)
const float R0 = 10000;
// 25°C时的开尔文温度
const float T0 = 298.15;
// ADC参考电压(伏特)
const float ADC_REF_VOLTAGE = 5.0; // 根据您的Arduino板的参考电压调整
// 读取热敏电阻的ADC值
float readThermistorADC() {
return analogRead(thermistorPin);
}
// 将ADC值转换为电压
float voltageFromADC(float adcValue) {
return adcValue * (ADC_REF_VOLTAGE / 1023.0);
}
// 将电压转换为电阻
float resistanceFromVoltage(float voltage, float pullUpResistor) {
return (pullUpResistor * voltage) / (ADC_REF_VOLTAGE - voltage);
}
// 计算温度
float calculateTemperature(float resistance) {
float lnR = log(resistance / R0);
float T = (1 / (lnR / B + 1 / T0)) - 273.15;
return T;
}
void setup() {
Serial.begin(9600);
}
void loop() {
float adcValue = readThermistorADC();
float voltage = voltageFromADC(adcValue);
float resistance = resistanceFromVoltage(voltage, 10000); // 假设上拉电阻为10K
float temperature = calculateTemperature(resistance);
Serial.print("Temperature: ");
Serial.print(temperature);
Serial.println(" C");
delay(1000);
}Loading
st-nucleo-l031k6
st-nucleo-l031k6