Skip to content

Instantly share code, notes, and snippets.

@codelectron
Last active April 23, 2018 19:14
Show Gist options
  • Save codelectron/5de6f618a153ff9b7bd2e0e45b342db1 to your computer and use it in GitHub Desktop.
Save codelectron/5de6f618a153ff9b7bd2e0e45b342db1 to your computer and use it in GitHub Desktop.
import RPi.GPIO as GPIO
from luma.core.interface.serial import i2c
from luma.core.render import canvas
from luma.oled.device import ssd1306, ssd1325, ssd1331, sh1106
import time
GPIO.setmode(GPIO.BCM)
GPIO_TRIGGER = 23
GPIO_ECHO = 24
GPIO.setup(GPIO_TRIGGER, GPIO.OUT)
GPIO.setup(GPIO_ECHO, GPIO.IN)
serial = i2c(port=1, address=0x3C)
device = ssd1306(serial, rotate=0)
def distance():
GPIO.output(GPIO_TRIGGER, True)
# set Trigger after 0.01ms to LOW
time.sleep(0.00001)
GPIO.output(GPIO_TRIGGER, False)
StartTime = time.time()
StopTime = time.time()
while GPIO.input(GPIO_ECHO) == 0:
StartTime = time.time()
# save time of arrival
while GPIO.input(GPIO_ECHO) == 1:
StopTime = time.time()
# time difference between start and arrival
TimeElapsed = StopTime - StartTime
# multiply with the sonic speed (34300 cm/s)
# and divide by 2, because there and back
distance = (TimeElapsed * 34300) / 2
return distance
if __name__ == '__main__':
try:
while True:
dist = distance()
print ("Measured Distance = %.1f cm" % dist)
with canvas(device) as draw:
draw.rectangle(device.bounding_box, outline="white", fill="black")
draw.text((10, 40), "Distance = %.1f cm"%dist, fill="white")
time.sleep(0.20)
# Reset by pressing CTRL + C
except KeyboardInterrupt:
print("Measurement stopped by User")
GPIO.cleanup()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment