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

#Sensor lib
from w1thermsensor import W1ThermSensor

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

from time import sleep

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

#################DS18B20 object creat##################################
#method 1：need to know the address of sersor
#DS18B20 = W1ThermSensor(W1ThermSensor.THERM_SENSOR_DS18B20, "000005e35af8")

#method 2：No need to know the sensor address, only 1 sensor is connected
DS18B20=W1ThermSensor()

while True:

    temperature = DS18B20.get_temperature() #data collection
    
    #oled displays temperature information, retains 2 decimal places
    with canvas(device) as draw:
        draw.text((0, 0),  '01Studio', fill="white")
        draw.text((0, 15), 'Temp test:', fill="white")
        draw.text((0, 40), '%.2f'%temperature+' C', fill="white")
    
    print('%.2f'%temperature) #print
    
    sleep(2) #Collection interval 2 seconds