Skip to content
Snippets Groups Projects
Commit f5705842 authored by LANGLAIS Charlotte's avatar LANGLAIS Charlotte
Browse files

Upload New File

parent 2ffc23d9
No related branches found
No related tags found
No related merge requests found
import time
import pycom
from machine import enable_irq, disable_irq, Pin
#Classe appelée pour le retour des données
class DTHResult:
ERR_NO_ERROR = 0
ERR_MISSING_DATA = 1
ERR_CRC = 2
error_code = ERR_NO_ERROR
temperature = -1
humidity = -1
def __init__(self, error_code, temperature, humidity):
self.error_code = error_code
self.temperature = temperature
self.humidity = humidity
def is_valid(self):
return self.error_code == DTHResult.ERR_NO_ERROR
#Classe de calcul des valeurs du capteur
class DTH:
def __init__(self, pin):
self.__pin = Pin(pin, mode=Pin.OPEN_DRAIN)
self.__pin(1)
time.sleep(1.0)
def read(self):
self.__send_and_sleep(0, 0.019)
data = pycom.pulses_get(self.__pin,100)
self.__pin.init(Pin.OPEN_DRAIN)
self.__pin(1)
bits = []
for a,b in data:
if a ==1 and 18 <= b <= 28:
bits.append(0)
if a ==1 and 65 <= b <= 75:
bits.append(1)
if len(bits) != 40:
return DTHResult(DTHResult.ERR_MISSING_DATA, 0, 0)
# Calcul des bytes
the_bytes = self.__bits_to_bytes(bits)
# calcul checksum et test
checksum = self.__calculate_checksum(the_bytes)
if the_bytes[4] != checksum:
return DTHResult(DTHResult.ERR_CRC, 0, 0)
# Retour des données
[int_rh, dec_rh, int_t, dec_t, csum] = the_bytes
rh = int_rh #dht11 20% ~ 90%
t = int_t #dht11 0..50°C
return DTHResult(DTHResult.ERR_NO_ERROR, t, rh)
def __send_and_sleep(self, output, mysleep):
self.__pin(output)
time.sleep(mysleep)
def __bits_to_bytes(self, bits):
the_bytes = []
byte = 0
for i in range(0, len(bits)):
byte = byte << 1
if (bits[i]):
byte = byte | 1
else:
byte = byte | 0
if ((i + 1) % 8 == 0):
the_bytes.append(byte)
byte = 0
return the_bytes
def __calculate_checksum(self, the_bytes):
return the_bytes[0] + the_bytes[1] + the_bytes[2] + the_bytes[3] & 255
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment