from machine import Pin, time_pulse_us, SoftI2C
from time import sleep, sleep_us
from ssd1306 import SSD1306_I2C
Trigger = Pin(23,Pin.OUT)
Echo = Pin(19,Pin.IN)
I2C_ADDR = 0x3C
i2c = SoftI2C(scl=Pin(22), sda=Pin(21), freq=100000) #initializing the I2C method for ESP32
#i2c = I2C(scl=Pin(5), sda=Pin(4), freq=10000) #initializing the I2C method for ESP8266
oled_width = 128
oled_height = 64
oled = SSD1306_I2C(oled_width, oled_height, i2c, I2C_ADDR)
while True:
Trigger.value(0)
sleep_us(2)
Trigger.value(1)
sleep_us(10)
Trigger.value(0)
twoWayTime = time_pulse_us(Echo,1)
distance = (twoWayTime * 0.034)/2
print('Distance in cm: ', distance)
oled.text("Distance in cm: ", 0, 0, 1)
oled.text(str(distance), 10, 20, 1)
oled.show()
sleep(1)