4 * Copyright 2004, 2005 Develer S.r.l. (http://www.de+veler.com/)
8 * \brief Driver for NTC (reads a temperature through an ADC)
12 * \author Giovanni Bajo <rasky@develer.com>
13 * \author Francesco Sacchi <batt@develer.com>
16 * This module handles an external NTC bound to an AD converter. As usual,
17 * it relies on a low-level API (ntc_hw_*) (see below):
23 *#* Revision 1.1 2005/11/04 17:59:47 bernie
24 *#* Import into DevLib.
26 *#* Revision 1.1 2005/05/24 09:17:58 batt
27 *#* Move drivers to top-level.
34 #include <cfg/debug.h>
36 DB(bool ntc_initialized;)
39 * Find in a table of values \a orig_table of size \a size, the index which
40 * value is less or equal to \a val.
42 * \retval 0 When \a val is higher than the first table entry.
43 * \retval size When \a val is lower than the last table entry.
44 * \retval 1..size-1 When \a val is within the table.
46 static size_t upper_bound(const res_t *orig_table, size_t size, res_t val)
48 const res_t *table = orig_table;
52 size_t pos = size / 2;
62 return table - orig_table;
67 * Read the temperature for the NTC channel \a dev.
68 * First read the resistence of the NTC through ntc_hw_read(), then,
69 * for the conversion from resistance to temperature, since the formula
70 * varies from device to device, we implemented a generic system using
71 * a table of data which maps temperature (index) to resistance (data).
72 * The range of the table (min/max temperature) and the step
73 * (temperature difference between two consecutive elements of the table)
74 * is variable and can be specified. Notice that values inbetween the
75 * table elements are still possible as the library does a linear
76 * interpolation using the actual calculated resistance to find out
77 * the exact temperature.
79 * The low-level API provides a function to get access to a description
80 * of the NTC (ntc_hw_getInfo()), including the resistance table.
83 deg_t ntc_read(NtcDev dev)
85 const NtcHwInfo* hw = ntc_hw_getInfo(dev);
86 const res_t* r = hw->resistances;
92 rx = ntc_hw_read(dev);
95 i = upper_bound(r, hw->num_resistances, rx);
96 ASSERT(i <= hw->num_resistances);
98 if (i >= hw->num_resistances)
99 return NTC_SHORT_CIRCUIT;
101 return NTC_OPEN_CIRCUIT;
104 * Interpolated value in 0.1 degrees multiplied by 10:
106 * ---------- = ----------------
107 * (rx - r[i]) (r[i-1] - r [i])
110 tmp = 10 * hw->degrees_step * (rx - r[i]) / (r[i - 1] - r[i]);
113 * degrees = integer part corresponding to the superior index
114 * in the table multiplied by 10
115 * - decimal part interpolated (already multiplied by 10)
117 degrees = (i * hw->degrees_step + hw->degrees_min) * 10 - (int)(tmp);
119 //kprintf("dev= %d, I=%d, degrees = %d\n", dev, i , degrees);
131 DB(ntc_initialized = true;)