from machine import Pin,I2C # Connecting to pins and i2c
from hcsr04 import HCSR04 # Conecting to the ultrasonic sensor
import ssd1306 # The library for the OLED
import time # So we can set up a delay
i2c = I2C(0, sda=Pin(16), scl=Pin(17)) # Setup i2c and tell it 0or1, sdapin & sclpin
oled = ssd1306.SSD1306_I2C(126,64,i2c) # Setup oled 126 x 64 pix on i2c
sensor = HCSR04(trigger_pin=2, echo_pin=3, echo_timeout_us=10000) # Digital pins
counter = 0 # Initialise counter to 0
while True:
oled.fill(0) # Blank the screen
oled.text("Count {}".format(counter), 10,20)
distance = sensor.distance_cm()
truncDist = (repr(round(distance,1))) # straight round gives wierd result, found solution on net.
oled.text("Dist {}".format (truncDist),10,40)
oled.show() # Write to the screen
counter += 1 # Increment counter by 1
time.sleep(0.5) # Wait for .5 sec before looping back to fill()
# Look up method ("String {}".format(variable),0,0) 0,0 is the position
# {} must be a place holder, .format() seems to convert to a string
# the common method is to convert the integer to string
# variable = 12.34
# variable_string = str(variable)
# oled.text(variable_string, 0, 0)
# oled.show()
# math.trunc(distance)