Sensor de temperatura y humedad

Sensor de temperatura y humedad

Aunque ya hicimos una entrada explicando que es un sensor de temperatura y ya vimos como utilizarlo con el sistema embebido que creamos para la Raspberry PI. En este caso vamos a utilizarlo con Python, y con el sistema operativo Raspbian. Para ello esta vez vamos a probar el sensor SHT21 que se comunica también por i2c.

Otras características del SHT21:

  • Presenta una resolución de la humedad relativa de un 0,04%, y una resolución de la temperatura de 0,01 ºC.
  • Rango de temperatura: -40 a 125 ºC
  • Rango humedad relativa: 0 -100%
  • Tensión de Alimentación: 3 V

El código quedaría de la siguiente manera:

#!/usr/bin/python
# -*- coding: utf-8 -*-
#################################################
#                                               #
# Temperature/Humidity control module  SHT21    #
# Authors: Ismael Tobar and Raquel Muñoz        #
#                                               #
#################################################

import smbus
from time import sleep
import threading
import register

#------i2c address of the transducer-----
TEMPERATURE_HUMIDITY_ADDRESS = 0x40
#------i2c commands of the transdcuer-----
READ_TEMPERATURE = 0xF3
READ_HUMIDITY= 0xF5
DO_SOFT_RESET = 0xFE
#------i2c bus-------
i2c = 0
#Variables
th_temperature = 0   #It's the variable that store the measure of the temperature (in ºC by default)
th_humidity = 0      #It's the variable that store the measure of the humidity in (%)
stop_thread = True  #It's the variable than stop the thread of the transducer
status = DISCONNECTED #It's a variable that indicate the error state of this transducer
units = 0 #It's a variable that indicates the units of the temperature taken by the transducer, 0 -> ºC, 1 -> K
counter = 0 #It's a variable that allows to register datas into a file, certanin number of times

#status variables
DISCONNECTED = 0
CONNECTED_OK = 1
CONNECTED_ERROR = 2

#the necessary settings are set , such as i2c bus
def setup():
    global i2c
    global status
    global units
    try:
        i2c = smbus.SMBus(1)
        i2c.write_byte(TEMPERATURE_HUMIDITY_ADDRESS, DO_SOFT_RESET) #A soft reset is done as the datasheet advices you
        sleep(0.015)
        print("TH: Setup")
        units = 0
        status = CONNECTED_OK
    except Exception as e:
        print ("TH: Error creating connection to i2c")
        print (e)
        status = CONNECTED_ERROR

#Change units f the temperature between ºC or K (u = 0 -> means ºC, u = 1 -> means K)
def change_units_t(u):
    global units
    if (0 <= u <= 1):
        units = u

#The transducer takes a measure of the temperature
def read_temperature():
    global th_temperature
    global status
    try:    
        i2c.write_byte(TEMPERATURE_HUMIDITY_ADDRESS, READ_TEMPERATURE)
        sleep(0.250) #It's the time that takes to the transducer to do a measure
        ran1 = i2c.read_byte(TEMPERATURE_HUMIDITY_ADDRESS)
        ran2 = i2c.read_byte(TEMPERATURE_HUMIDITY_ADDRESS)
        data = (ran1 << 8) + ran2
        #T =-46.82 + (172.72 * (data/2^16))  The formula has been obtained from the datasheet
        data *= 175.72
        data /= 1 << 16 # divide by 2^16
        data-= 46.85
        th_temperature = int(data)
        if units == 1:  #We convert the degrees Celsius into kelvin
            th_temperature += 273
    except IOError, e:
        print ("TH: Error reading temperature")
        print (e)
        status = CONNECTED_ERROR  

#The transducer takes a measure of the humidity
def read_humidity():   
    global th_humidity
    global status
    try:
        i2c.write_byte(TEMPERATURE_HUMIDITY_ADDRESS, READ_HUMIDITY)
        sleep(0.250) #It's the time that takes to the transducer to do a measure
        ran1 = i2c.read_byte(TEMPERATURE_HUMIDITY_ADDRESS)
        ran2 = i2c.read_byte(TEMPERATURE_HUMIDITY_ADDRESS)
        data = (ran1 << 8) + ran2
        #RH = -6 + (125 * (SRH / 2 ^16)) The formula has been obtained from the datasheet
        data *= 125
        data /= 1 << 16 # divide by 2^16
        data -= 6
        th_humidity = int(data)
    except IOError, e:
        print ("TH: Error reading humidity")
        print (e)
        status = CONNECTED_ERROR

#Function that the thread executes
def thread_humidity_temperature():
    global counter
    global status
    counter = 0
    while stop_thread == False:
        try:
            counter += 1
            read_humidity()
            read_temperature()
            """if counter == 10:
                register.writeFile(str(th_temperature))
                register.writeFile(str(th_humidity))
                counter = 0"""
            sleep(1)
        except Exception as e:
            print("TH: error thread temperature_humidity_sensor ")
            print(e)
            status = CONNECTED_ERROR
    print("TH: Temperature and humidity sensor thread stopped ")

#The thread of the transducer is started
def start_thread_th():
    global stop_thread
    global status
    try:
        if stop_thread == True:
            stop_thread = False
            thread_sensor_th = threading.Thread(target=thread_humidity_temperature)
            thread_sensor_th.start()
            print('TH started')
    except Exception as e:
        print("TH: error starting thread temperature_humidity_sensor ")
        print(e)
        status = CONNECTED_ERROR

#The thread of the transducer is stop
def stop_thread_th():
    global stop_thread     
    stop_thread = True

if __name__ == "__main__":
    setup()
    terminate = False
    start_thread_th()
    while terminate == False:
        sleep(0.1)
        seconds = input('Enter how many seconds you want be taking measures? (0 to exit) : ')
        if seconds != 0:
            for i in range (0,seconds):
                print("Temperature : ",int(th_temperature))
                print("Humidity : ",int(th_humidity))
                sleep(1)
        else:
            terminate = True
            stop_thread_th()
    print('TH: Exit temperature and humidity sensor')

En nuestro caso este sensor forma parte del vehículo robotizado que hemos desarrollado.