# Display Image & text on I2C driven ssd1306 OLED display
from machine import Pin, I2C
from ssd1306 import SSD1306_I2C
import framebuf
import machine
import utime
trig = Pin(1, Pin.OUT) # trig pin
echo = Pin(0, Pin.IN) # echo pin
Buzzer = Pin(18, Pin.OUT) # Buzzer at pin 18
Buzzer.value(0) # Turn OFF buzzer
WIDTH = 128 # oled display width
HEIGHT = 64 # oled display height
i2c = I2C(0, scl=Pin(17), sda=Pin(16), freq=200000) # Init I2C using pins GP8 & GP9 (default I2C0 pins)
print("I2C Address : "+hex(i2c.scan()[0]).upper()) # Display device address
print("I2C Configuration: "+str(i2c)) # Display I2C config
oled = SSD1306_I2C(WIDTH, HEIGHT, i2c) # Init oled display
while True:
# Clear the oled display in case it has junk on it.
oled.fill(0)
trig.value(0)
utime.sleep_us(5) # Wait until settled
trig.value(1) # Send trig pulse
utime.sleep_us(10) # 10 microseconds
trig.value(0) # Remove trig pulse
while echo.value() == 0: # Wait for echo 1
pass
Tmrstrt = utime.ticks_us()
while echo.value() == 1: # Wait for echo 0
pass
Tmrend = utime.ticks_us()
Duration = utime.ticks_diff(Tmrend, Tmrstrt)
distancecm = Duration * 0.0171
# Add some text
oled.text("Distance: ", 0, 0)
oled.text(str(distancecm), 0, 20)
# Finally update the oled display so the image & text is displayed
oled.show()
if distance > 100:
dely = 0
elif distance > 70 and distance < 90:
dely = 600
elif distance > 50 and distance < 70:
dely = 400
elif distance > 30 and distance < 50:
dely = 300
elif distance > 10 and distance < 30:
dely = 200
elif distance < 10:
dely = 10
if distance < 100:
Buzzer.value(1)
utime.sleep_ms(dely)
Buzzer.value(0)
utime.sleep_ms(dely)