from machine import Pin, SoftI2C, time_pulse_us
import ssd1306
import time
# Constants
SPACE_EMPTY_THRESHOLD_CM = 50 # Distance threshold to consider space empty
PARKING_SPACES = 3 # Number of parking spaces to monitor
UPDATE_INTERVAL = 1 # Update interval in seconds
# OLED Display Setup
i2c = SoftI2C(scl=Pin(22), sda=Pin(21))
oled = ssd1306.SSD1306_I2C(128, 64, i2c)
# Parking Sensor Setup
# Format: (trigger_pin, echo_pin)
parking_sensors = [
(Pin(15, Pin.OUT), Pin(2, Pin.IN)), # Space 1
(Pin(4, Pin.OUT), Pin(16, Pin.IN)), # Space 2
(Pin(17, Pin.OUT), Pin(5, Pin.IN)) # Space 3
]
# Variables to track parking status
space_status = [False] * PARKING_SPACES # False = empty, True = occupied
available_spaces = PARKING_SPACES
def measure_distance(trigger, echo):
"""Measure distance using ultrasonic sensor"""
# Send pulse
trigger.off()
time.sleep_us(2)
trigger.on()
time.sleep_us(10)
trigger.off()
# Measure echo pulse duration
duration = time_pulse_us(echo, 1, 30000) # Timeout for 30ms (~5m)
# Calculate distance in cm (speed of sound 343m/s = 0.0343cm/µs)
distance = duration * 0.0343 / 2
return distance if duration > 0 else float('inf')
def update_display():
"""Update the OLED display with current parking status"""
oled.fill(0)
# Title
oled.text("Smart Parking", 0, 0)
oled.text("Assistant", 0, 10)
# Available spaces
oled.text(f"Available: {available_spaces}/{PARKING_SPACES}", 0, 25)
# Individual space status
for i in range(PARKING_SPACES):
status = "OCCUPIED" if space_status[i] else "EMPTY"
oled.text(f"Space {i+1}: {status}", 0, 35 + i * 10)
# Footer with instructions
if available_spaces == 0:
oled.text("FULL - Try Later", 0, 55)
else:
oled.text("Spaces Available!", 0, 55)
oled.show()
def check_parking_spaces():
"""Check all parking spaces and update status"""
global available_spaces
available_spaces = 0
for i in range(PARKING_SPACES):
trigger, echo = parking_sensors[i]
distance = measure_distance(trigger, echo)
# Update space status
space_status[i] = distance < SPACE_EMPTY_THRESHOLD_CM
# Count available spaces
if not space_status[i]:
available_spaces += 1
def main():
"""Main program loop"""
# Initial display update
update_display()
while True:
# Check parking spaces
check_parking_spaces()
# Update display
update_display()
# Wait before next update
time.sleep(UPDATE_INTERVAL)
if __name__ == "__main__":
main()