AskSin++
Ntc.h
1 //- -----------------------------------------------------------------------------------------------------------------------
2 // AskSin++
3 // 2018-04-03 papa Creative Commons - http://creativecommons.org/licenses/by-nc-sa/3.0/de/
4 //- -----------------------------------------------------------------------------------------------------------------------
5 
6 #ifndef __SENSORS_NTC_h__
7 #define __SENSORS_NTC_h__
8 
9 #include <Sensors.h>
10 
11 namespace as {
12 
13 /*
14  * NTC needs to be connected like shown here: http://playground.arduino.cc/uploads/ComponentLib/simple10ktherm_schem_new.png
15 
16  * SENSEPIN is the analog pin
17  * ACTIVATEPIN is a output pin to power up the NTC only while measuring. Use 0 if the NTC is connected to VCC and not to a pin.
18  * R0 is the resitance both of the NTC and of the second resistor
19  * B is a material based number of the NTC. Look it up in the datasheet of the NTC. E.g. the ATC 103AT-2 has a B of 3435
20  * T0 is the temperature where the NTC has the resistance R0. In most cases this is 25°C.
21  * OVERSAMPLING are the additional oversampled bits, e.g. choosing 2 will increase the internal sample size of the ATmega ADC from 10 bit to 12 bit.
22  */
23 
24 template <uint8_t SENSEPIN,uint32_t R0=10000,uint16_t B=3435,uint8_t ACTIVATEPIN=0,int8_t T0=25,uint8_t OVERSAMPLING=0>
25 class Ntc : public Temperature {
26  const int32_t _t0Abs = T0 * 10 + 2732;
27  const int32_t _max_ref = (1 << (10 + OVERSAMPLING)) - 10 - OVERSAMPLING;
28 
29 public:
30  Ntc () {}
31 
32  void init () {
33  pinMode(SENSEPIN, INPUT);
34  }
35 
36  bool measure (__attribute__((unused)) bool async=false) {
37  uint32_t vo = 0;
38 
39  if (ACTIVATEPIN) {
40  pinMode(ACTIVATEPIN, OUTPUT);
41  digitalWrite(ACTIVATEPIN, HIGH);
42  }
43 
44  for (uint16_t i = 0; i < 1 << (OVERSAMPLING * 2); i++) {
45  vo += analogRead(SENSEPIN);
46  }
47 
48  if (ACTIVATEPIN) {
49  digitalWrite(ACTIVATEPIN, LOW);
50  }
51 
52  if (OVERSAMPLING) {
53  vo = vo >> OVERSAMPLING;
54  }
55 
56  vo = _max_ref - vo;
57 
58  float rNtc = vo / (float)(_max_ref - vo);
59  _temperature = 10 * B * _t0Abs / (10 * B + (int16_t)(log(rNtc) * _t0Abs)) - 2732;
60 
61  return true;
62  }
63 };
64 }
65 
66 #endif
as::Temperature
Definition: Sensors.h:30
as::Ntc
Definition: Ntc.h:25