56 lines
1.4 KiB
C
56 lines
1.4 KiB
C
|
#include <stdio.h>
|
||
|
#include <stdint.h>
|
||
|
|
||
|
#include <math.h>
|
||
|
|
||
|
#include <fxp.h>
|
||
|
|
||
|
static fxp_t adc_val_to_pin_voltage(uint16_t adc_val)
|
||
|
{
|
||
|
return fxp_div(
|
||
|
fxp_mult(FXP_FROM_INT((int32_t)adc_val), fxp_div(FXP_FROM_INT(33), FXP_FROM_INT(10))),
|
||
|
FXP_FROM_INT(4096));
|
||
|
}
|
||
|
|
||
|
|
||
|
static fxp_t calc_temperature_ntc(uint16_t adc_val)
|
||
|
{
|
||
|
// note: all resistor values in kΩ! The factor 1000 is removed from the numbers!
|
||
|
static const fxp_t ln_r_ntc_nom = 252323; // ln(47 kΩ) converted to fxp_t with 16 fractional bits
|
||
|
static const fxp_t r1 = FXP_FROM_INT(10);
|
||
|
static const fxp_t b_constant = FXP_FROM_INT(4125);
|
||
|
static const fxp_t ntc_temp_nom_inv = 220; // 1/(273.15+25) * 2**16
|
||
|
static const fxp_t celsius2kelvin = 17901158; // (273.15) * 2**16
|
||
|
|
||
|
fxp_t v_r1 = adc_val_to_pin_voltage(adc_val);
|
||
|
fxp_t v_ref = fxp_div(FXP_FROM_INT(33), FXP_FROM_INT(10));
|
||
|
|
||
|
fxp_t r_ntc = fxp_div(fxp_mult(fxp_sub(v_ref, v_r1), r1), v_r1);
|
||
|
|
||
|
fxp_t ln_r_ntc = fxp_from_float(logf(fxp_to_float(r_ntc)));
|
||
|
|
||
|
fxp_t temp_k = fxp_div(FXP_FROM_INT(1),
|
||
|
fxp_add(
|
||
|
fxp_div(
|
||
|
fxp_sub(
|
||
|
ln_r_ntc,
|
||
|
ln_r_ntc_nom),
|
||
|
b_constant),
|
||
|
ntc_temp_nom_inv));
|
||
|
|
||
|
return fxp_sub(temp_k, celsius2kelvin);
|
||
|
}
|
||
|
|
||
|
|
||
|
int main(void)
|
||
|
{
|
||
|
for(uint16_t adc_val = 128; adc_val < 4096; adc_val += 512) {
|
||
|
fxp_t temperature = calc_temperature_ntc(adc_val);
|
||
|
|
||
|
float tempf = fxp_to_float(temperature);
|
||
|
float voltf = adc_val * 3.3f / 4096.0f;
|
||
|
|
||
|
printf("%5.3f V => %7.2f °C\n", voltf, tempf);
|
||
|
}
|
||
|
}
|