Untitled

 avatar
unknown
plain_text
2 years ago
810 B
4
Indexable
from gpiozero import DistanceSensor
import pygame
import os
import time

# Initialize ultrasonic sensor
ultrasonic_sensor = DistanceSensor(echo=17, trigger=4)

# Initialize Pygame for displaying on VNC
pygame.init()
pygame.font.init()

# Set up the display
os.environ['SDL_VIDEODRIVER'] = 'dummy'
screen = pygame.display.set_mode((1, 1))

# Set up fonts
font = pygame.font.SysFont(None, 55)

def display_distance(distance):
    screen.fill((0, 0, 0))
    text = font.render(f"Distance: {distance:.2f} cm", True, (255, 255, 255))
    screen.blit(text, (10, 10))
    pygame.display.flip()

try:
    while True:
        distance = ultrasonic_sensor.distance * 100  # Convert to centimeters
        display_distance(distance)
        time.sleep(0.1)

except KeyboardInterrupt:
    pass

finally:
    pygame.quit()
Editor is loading...
Leave a Comment