from utime import sleep, sleep_us
from machine import SoftI2C, Pin, time_pulse_us
import oled
from ultrasonic import HCSR04
#i2c & oled
i2c = SoftI2C(scl=Pin(22), sda=Pin(21))
oled = oled.I2C(128, 64, i2c)
ultra = HCSR04(5, 18)
while True:
print(ultra.get_distance_cm(), " cm")
sleep(1)
print(ultra.get_distance_mm(), " mm")
sleep(1)
# # Init trigger pin (out)
# trigger_pin = Pin(5, mode=Pin.OUT, pull=None)
# trigger_pin.value(0)
# # Init echo pin (in)
# echo_pin = Pin(18, mode=Pin.IN, pull=None)
# def send_pulse_and_get_tof():
# # Send a 10us pulse
# trigger_pin.value(1)
# sleep_us(10)
# trigger_pin.value(0)
# try:
# pulse_time = time_pulse_us(echo_pin, 1, 30000)
# return pulse_time
# except OSError as ex:
# raise OSError('Error')
# while True:
# time_of_flight = send_pulse_and_get_tof()
# # To calculate the distance we get the time_of_flight and divide it by 2
# # (the pulse walk the distance twice) and by 29.1 because
# # the sound speed on air is 343.2 m/s, that It's equivalent to
# # 0.034320 cm/us that is 1cm each 29.1us
# distance_cm = int((time_of_flight / 2) // 29.1)
# oled.clear()
# oled.text('Distance: ' + str(distance_cm), 10, 3)
# oled.show()
# sleep(0.1)