'''
example name：Temperature and humidity sensor (DHT11)
version：v1.0
date：2020.3
Author：01Studio
Forum: forum.01studio.org
Description: Collect temperature and humidity data and display on oled.
'''

import Adafruit_DHT,time

#import luma module,oled lib
from luma.core.render import canvas
from luma.oled.device import ssd1306

#initialize oled，I2C1; the oled address is 0x3c
device = ssd1306(port=1, address=0x3C)

#set sensonr type, support:DHT11,DHT22 and AM2302
sensor=Adafruit_DHT.DHT11
  
#set GPIO
gpio=19

while True:    

    #Read sensor data, it will repeat 15 times if the reading fails, with an interval of 2 seconds
    humidity, temperature = Adafruit_DHT.read_retry(sensor, gpio)
    
    # In order to avoid occasional reading failure, first judge whether the reading is successful,
    # and then print the relevant data

    if humidity is not None and temperature is not None:
        #oled displays temperature and humidity information, retains 2 decimal places
        with canvas(device) as draw:
            draw.text((0, 0),  '01Studio', fill="white")
            draw.text((0, 15), 'DHT11 test:', fill="white")
            draw.text((0, 40), '%.1f'%temperature+' C'+'  '+'%.1f'%humidity+' %', fill="white")
        print('Temp={0:0.1f}*C  Humidity={1:0.1f}%'.format(temperature, humidity))

    else:
        with canvas(device) as draw:
            draw.text((0, 0),  '01Studio', fill="white")
            draw.text((0, 15), 'DHT11 test:', fill="white")
            draw.text((0, 40), 'Failed to read!', fill="white")
        
        print('Failed to get reading. Try again!')        
    
    time.sleep(2)
