import machine
import utime
import ssd1306
from machine import Pin, PWM, I2C
# Initialize I2C for OLED
i2c = I2C(0, scl=Pin(1), sda=Pin(0)) # Adjust pins if necessary
oled = ssd1306.SSD1306_I2C(128, 64, i2c)
# Initialize HC-SR04
trig = Pin(26, Pin.OUT)
echo = Pin(27, Pin.IN)
# Initialize Servo
servo = PWM(Pin(4))
servo.freq(50) # Standard frequency for servos
# Define servo positions (in duty cycle)
OPEN_POSITION = 65535 * 0.5 # Adjust these values based on your servo
CLOSED_POSITION = 65535 * 0.2 # Adjust these values based on your servo
def get_distance():
trig.low()
utime.sleep_us(2)
trig.high()
utime.sleep_us(10)
trig.low()
while echo.value() == 0:
pulse_start = utime.ticks_us()
while echo.value() == 1:
pulse_end = utime.ticks_us()
pulse_duration = utime.ticks_diff(pulse_end, pulse_start)
distance = pulse_duration * 0.0343 / 2 # Convert to cm
return distance
def update_display(free_slots, gate_status):
oled.fill(0)
oled.text("Free Slots: {}".format(free_slots), 0, 0)
oled.text("Gate: {}".format(gate_status), 0, 10)
oled.show()
def control_gate(free_slots):
if free_slots > 0:
# Open gate
servo.duty_u16(OPEN_POSITION)
return "Open"
else:
# Close gate
servo.duty_u16(CLOSED_POSITION)
return "Closed"
def main():
num_slots = 10 # Total number of parking slots
occupied_slots = 0
while True:
free_slots = num_slots - occupied_slots
distance = get_distance()
if distance < 10: # Adjust this threshold as needed
occupied_slots += 1
print("vehicle detected gate opening")
else:
occupied_slots = max(0, occupied_slots - 1)
print("vehicle not detected")
gate_status = int(control_gate(free_slots))
update_display(free_slots, gate_status)
utime.sleep(2) # Check every 2 seconds
if __name__ == "__main__":
main()