'''
example name：Ultrasonic sensor
version：v1.0
date：2020.3
Author：01Studio
Description: Measure the distance and display it in oled.
Forum: forum.01studio.org
'''


from gpiozero import DistanceSensor

#import luma,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)

#creat DistanceSensor object
sensor = DistanceSensor(echo=15, trigger=14)

while True:

    #Change the unit to cm
    distance = sensor.distance *100

    #Display the result to 2 decimal places
    with canvas(device) as draw:
        draw.text((0, 0),  '01Studio', fill="white")
        draw.text((0, 15), 'Distance test:', fill="white")
        draw.text((0, 35), str("%.2f"%distance)+' CM' , fill="white")

    print('Distance to nearest object is %.2f'%distance, 'CM')

    sleep(0.5) #Collection interval 500 milliseconds
