26 October, 2014

How to use a thermistor or temperature sensor with Arduino: Code for the NTC/PTC types

Checking the operation of the program
One of the most common applications of Arduino is an electronic temperature control via a simple thermistor (temperature sensor), for example if we want to activate a fan when the temperature rises to a certain value in a computer / engine, or activated by an relay a circulator motor in a boiler when we detect that the temperature is rising (and thus the fire is on), as we did in home boiler with AKO or Keld thermostats, only with Arduino will not only allow us to activate a device, but allowing us much more play, controlling and managing other parameters for our stove, such as temperature of the fumes, or air injected into the combustion chamber, etc, as already explained us Oscar Gonzalez in BricoGeek from a project from Xoel (from Asturias).
A thermistor (thermistor) is simply a resistor whose resistance varies as its temperature varies (though non-linearly); there are many kinds, but in this post talk about one NTC (Negative, whose resistance value decreases as the temperature increases), and measure different temperature ranges of -50 to + 99 ° C in this case.If we measure a higher temperature, we would need a thermocouple type K or J, but we'll see later.  
But to use a thermistor whatever we can get, is not enough to measure the value of resistance and apply a rule of three, because as we said, is not a linear (but curved) value, with the biggest differences resistance with increasing temperature so hyperbolic.

To use a thermistor, or know their values ​​(datasheet), or we have to approach them; according to the formula Steinhart-Hart, we have to find a value, called β (Beta) (so-called value of characteristic temperature of the material), and use it along with your formula to get the C to a given value. Here is very well explained , and this explained the Steinhart-Hart formula .

Although it seems difficult to understand for those who give them bad math (like me), but do not worry, in the end you have a program that you can use and just change the header data (values ​​of two points, the resistance of your thermistor 25 and the actual value of your Arduino 5Vdc and little else) will be able to use it in your project without having to understand the formulas involved, but I prefer to go into detail for those who like it as much as me "why of things. "

But how do we calculate the β value? 
To obtain the value of β, using the Steinhart-Hart formula, give the values ​​of resistance and temperature at two different points, as far as possible from each other, for greater accuracy. The formula tells us that β is equal to:

Obtaining resistance values ​​of 25 and 100 (for example), we get β  

We can use ice to the temperature of 0 ° and boiling water on the fire for the 100, take the value of the thermistor resistance at those two points (waiting a few minutes until the resistance value is more or less stable, will be when the thermistor temperature has been reached).
Note: Please note that at higher altitudes, water boils at a lower temperature, may be 5 or 10 ° C difference, it is best to use a thermometer in turn calibrated to compare.
In my case I wanted to reuse a couple of AKO 14901 sensors, and obtaining the values ​​of resistance with a tester that has given me 10330 ohms at 25 ° C was approx. (Or what is the same, 10K ohms): 

I used a thermometer that had room to get closer to reality (and the same error as the same, because it is not calibrated, but it's something).

And as close to 100 ° C at 96 ° C approx. a resistance value of 970 ohms: 

So if we get β, leave us (using google as a calculator): 

That is, in my case, ln (970/10 330) / ((1 / 370.15) - (1 / 298.15)) = 3 625.81 

The calculation of the constant β will do at the beginning of the program we will Arduino, based on T1, R1, R2 and T2 (the two points we can get), constants, and thus avoid making too many calculations (must reserve capacity process for other more important) duties.

To display the values, I used the economic and LCD screen Versatile Nokia 5110 84x48 pixels ;to learn how to use it and use its capacity is the best thing to recurráis Jose Manuel tutorial . 

Based on code Torrales Rafael , I added code so that the program will automatically calculate the data we needed for our thermistor, so we just have to give the values ​​of the two points: 

Universal program for NTC / PTC: 

/*  ==================================================================

    Sketch universal para el control de termistores.
  Autor: David Losada, basado en trabajos de Rafael Torrales y Antonio Moles.
  Version: 0.1
  Fecha: 2 de julio de 2012
  Descripcion: termometro con termistor NTC y pantalla LCD grafica Nokia 5110
               de 84x48 pixeles

    ==================================================================   */

#include //Necesarias para usar la pantalla LCD Nokia

// pin 3 - Serial clock out (SCLK)
// pin 4 - Serial data out (DIN)
// pin 5 - Data/Command select (D/C)
// pin 7 - LCD chip select (CS)
// pin 6 - LCD reset (RST)
Adafruit_PCD8544 display = Adafruit_PCD8544(7, 6, 5, 4, 3);

//Control temperatura
//Para ahorrar cálculos, lo vamos a calcular antes del programa
const float TPto1 = -6; //Temperatura en ºC punto 1
const float RPto1 = 40000; // Ohms en punto 1
const float TPto2 = 96; // Temp. punto 2
const float RPto2 = 970; // Ohms en punto 2
const float resistor = 10290; //El valor en ohmnios de la resistencia del termistor a 25ºC
const float voltage = 4.83; // El voltaje real en el punto 5Vcc de tu placa Arduino
//Para ahorrar cálculos lo definimos como constante en esta parte del programa
const float K= 273.15; //Para pasar a grados Kelvin
const float e = 2.718281828459045; //Constante matemática 
const float B = log(RPto2/RPto1)/(1/(TPto2+K)-(1/(TPto1+K))); //Valor Beta de tu termistor
const float unodivr = 1/(resistor * pow(e,(-B/298.15))); //Con pow elevamos e al resultado

float T = 0; //Declaramos la variable Temperatura
float tmedia; //Variable para calcular media
int cnt; //temperatura media y contador
int grados, decimas; //Para ponerle coma al resultado (en español)

int sensorPin = A0; // Selecciona la entrada para el termistor
int sensorValue = 0; // Aquí almacenamos el valor del sensor

void setup()   { 
  // Iniciamos comunicacion serie con pantalla
  // Iniciamos comunicacion con la pantalla

  // Establecemos el contraste

  // Mostramos la pantalla de inicio durante 2 segundos
  // borramos la pantalla

void loop() 
  //float B= (RPto2/RPto1);//(1/(TPto2+K)-(1/(TPto1+K)));
// Parte 1:  Leemos el puerto analógico 0 y convertimos el valor en voltios.
   sensorValue = analogRead(sensorPin); //Leemos analógico 0    
   tmedia=0; //Inicializamos variable
   // medimos la temperatura 10 veces y la almacenamos en tmedia
    for ( cnt=0; cnt<10 cnt="" span="">
      sensorValue = analogRead(sensorPin);
    // calculamos la media de las medidas
    //Convertimos a voltios :)
    float v2 = (voltage*float(tmedia))/1024.0f;    
 // Parte 2: Calcular la resistencia con el valor de los voltios mediante la ecuación del divisor de voltaje
  //voltage = 4.83
  //R2 = 10000
  //R1 = Thermistor resistance
  //V2= v2
  //so V2=(R2*V)/(R1+R2)
  //and r1=((r2*v)/v2)-r2 <--final span="">
  float r1a = (voltage*float(resistor))/v2;  
  float r1 =r1a - resistor;

  //Parte 3: Calcular la temperatura basandose en la ecuación Steinhart-Hart y la ecuación del valor Beta.
  // T=B/ln(r1/rinfinit)

  float T = B/log(r1*unodivr);
  T=T-273.15; //Convertimos a ºC y ya tenemos la temperatura
    // ahora obtenemos la parte entera
    // y las decimas de grado son el resto
    // Y por ultimo lo mandamos a la pantalla LCD
    display.print(" ");
    //display.print("       ");


Would appreciate any suggestions for improvement in the hicierais code in the remarks I too share in GoogleDocs for those who want to correct a mistake and leave your own version. 

So much for the theoretical part, the problem, the calculations and the resulting code. Now let's check if it works with a plate of work where the screen and connect the sensor. 

Hands: Connecting it all 

If you are new to the Arduino world, it is best that you read, investiguéis and probéis examples and tutorials of your page Arduino.cc and of Ardumanía . 

The thermistor must be placed as follows: 

  (Ground) ---- (10k-Resister) ------- | ------- (Thermistor) ---- (+ 5V)
                                 Analog Pin 0 

On the one hand to 5V on the Arduino and the other connected to the resistor of the same value that has the thermistor at 25 ° C (in this case 10KOhms) and derived that point we choose the analog input (e we indicate in the program). The other side of the resistor goes to ground (ground, GND on the Arduino). 

As stated Jose Manuel in his tutorial , connect the LCD with resistance 2K2 ohms (2200 ohms) in SCE (CS) and four 10K ohms in RST, D / C, DN and SCLK: 

Arduino showing the ambient temperature at the LCD
This screen is very versatile, but its libraries hold quite leaves us plenty of room to make a fairly complex program control. Detail of the connection of the cables: 

Right panel wiring resistance of 10 K that I used for the thermistor is (we have to use a resistor of the same value that the thermistor at 25). 

We program the Arduino IDE, and this is the result, the room temperature: 

If I compare to the previous room thermometer with a glass of hot water: 

And if we use a second sensor to compare and activate a relay or what we need? We could, for example, to obtain this result by connecting a second thermistor in A1, and duplicating parts of the code, but we'll see in another post: 

These tests and programs are the seeds of a possible open source caldera, where everyone can suggest improvements and modifications thereof, in which the entire operation is known and open to all. Anyone who wants to brainstorm and collaborate is welcome, to see if we can get a prototype boiler safe and popular to serve for different fuels (wood, pellets, etc). 
Provided they are not marketed, or if done, it is non-profit, we all win. 
As the content of the blog, all the information on this topic would share Creative Commons BY-SA Noncommercial. 

Tutorial Torrales Rafael in his blog; using a thermistor Arduino, Part 1 
Rafael Torrales Tutorial, 2nd part 
Calculators for beta, alpha values, etc in a thermistor 

Related links: 
Control circuit thermocouple type K and others; MAX6675 
Furnace temperature control with Arduino and MAX6675 
ttp: //arduino.cc/playground/ComponentLib/Thermistor 

To learn how to use a DC motor, relay servos, etc with Arduino 
Projects with Arduino 
Trucar servo 

Shops Arduino and Spanish components: 

No comments :

Post a Comment