首先要明确NTC热敏电阻的阻值是随温度升高,电阻降低的一个特性,加上拉电阻10K,不过一下子没有找到10K的上拉电阻,就用了一个8.2K的上拉电阻到3.3V,测温电阻一端接地,中间接stm32的PA1使用ADC测电压来计算温度。
使用AI辅助编程,竟然出现多处错误来误导我,让我搞了很久才搞定:

float adc_to_temperature()
{
    // Parameters for the thermistor
    const float beta = 3950.0;       // Beta coefficient for the thermistor
    const float R0 = 10000.0;        // Resistance at 25 degrees Celsius (in ohms)
    const float T0 = 25.0;           // Reference temperature in Celsius
    const float Vcc = 3.3;           // Supply voltage in volts
    //const float R_pull_up = 8800.0;  // Pull-up resistor value in ohms
    const float R_pull_up = 8200.0;  // Pull-up resistor value in ohms
    const float T0_K = T0 + 273.15; // Reference temperature in Kelvin
    // Convert ADC reading to voltage
	HAL_ADC_Start(&hadc1);
	uint32_t adc_reading =  HAL_ADC_GetValue(&hadc1);
	printf("ADC1 = %d\n",adc_reading);
    float V_adc = (adc_reading / 4095.0) * Vcc;
	printf("V_adc = %f\n", V_adc);

    // Calculate resistance of the thermistor
    //float R_th = R_pull_up * ((Vcc / V_adc) - 1); //AI给的错误程序
	float R_th = (V_adc * R_pull_up) / (Vcc - V_adc);//正确

	printf("R_th = %f\n", R_th);

// 	  Calculate temperature using the simplified formula
//    float T;
//    if (R_th > 0) {
//        T = (beta * T0) / (T0 * log(R_th / R0) + beta); //AI给的错误程序,
//竟然使用普通的温度直接计算。导致结果错误,应该使用开尔文温度计算
//    	printf("T = %f\n", T);
//    } else {
//        //T = NAN;  // Handle division by zero or invalid resistance
//        T = TARGET_TEMP;  // Handle division by zero or invalid resistance
//    }


    // Calculate temperature using the simplified formula
        float T_K;
        if (R_th > 0) {
            T_K = (beta * T0_K) / (T0_K * log(R_th / R0) + beta);//正确
        } else {
            T_K = TARGET_TEMP;  // Handle division by zero or invalid resistance
        }
	  	  float temperature_K = T_K;
	      float temperature_C = temperature_K - 273.15 - 1.5;//这个1.5是我自己做的误差矫正

	      printf("Temperature: %.2f K\n", temperature_K);
	      printf("Temperature: %.2f °C\n", temperature_C);

    return temperature_C;
}
Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐