Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
810 B
1
Indexable
Never
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()
Leave a Comment