from machine import Pin, I2C, PWM
from utime import sleep, sleep_us, time
import network
import urequests
from i2c_lcd import I2cLcd
# LCD Setup
I2C_ADDR = 0x27
i2c = I2C(0, scl=Pin(21), sda=Pin(20), freq=400000)
lcd = I2cLcd(i2c, I2C_ADDR, 4, 20)
print("LCD initialized.")
# Ultrasonic Sensor Setup (HC-SR04)
trigger = Pin(12, Pin.OUT)
echo = Pin(13, Pin.IN)
print("Ultrasonic Sensor initialized.")
# Servo Setup
servo = PWM(Pin(15))
servo.freq(50)
print("Servo initialized.")
# Keypad Setup
rows = [Pin(pin, Pin.OUT) for pin in [18, 19, 20, 21]]
cols = [Pin(pin, Pin.IN, Pin.PULL_UP) for pin in [22, 26, 27, 28]]
keys = [
['1', '2', '3', 'A'],
['4', '5', '6', 'B'],
['7', '8', '9', 'C'],
['*', '0', '#', 'D']
]
print("Keypad initialized.")
# Wi-Fi Setup
SSID = "Wokwi-GUEST"
PASSWORD = ""
ADAFRUIT_AIO_USERNAME = "tharunnv"
ADAFRUIT_AIO_KEY = "aio_uqnk18hiIB1r16iUxRXq24U49BcL"
AIO_FEED = f"{ADAFRUIT_AIO_USERNAME}/feeds/"
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
print("Attempting to connect to Wi-Fi...")
wlan.connect(SSID, PASSWORD)
timeout = 20 # Increased timeout
start_time = time()
while not wlan.isconnected():
if time() - start_time > timeout:
print("Wi-Fi connection timed out.")
return False
print("Connecting to Wi-Fi...") # Debug message
sleep(1)
print("Connected to Wi-Fi")
return True
def update_adafruit(status):
headers = {'X-AIO-Key': ADAFRUIT_AIO_KEY, 'Content-Type': 'application/json'}
data = {"value": status}
try:
response = urequests.post(AIO_FEED, json=data, headers=headers)
response.close()
print("Updated Adafruit IO:", status)
except Exception as e:
print("Failed to update Adafruit IO:", e)
# Read Keypad
def read_key():
for row in range(4):
rows[row].value(0)
for col in range(4):
if cols[col].value() == 0:
sleep(0.1) # Debounce
while cols[col].value() == 0:
pass
rows[row].value(1)
return keys[row][col]
rows[row].value(1)
return None
# Get OTP from Keypad
def get_otp():
lcd.clear()
lcd.putstr("Enter OTP: ")
otp = ""
while len(otp) < 4:
key = read_key()
if key:
otp += key
lcd.move_to(10 + len(otp), 1)
lcd.putstr("*")
return otp
# Function to measure distance using the ultrasonic sensor
def get_distance():
trigger.low()
sleep_us(2)
trigger.high()
sleep_us(10)
trigger.low()
pulse_start = 0
pulse_end = 0
timeout = time() + 0.1 # 100ms timeout
while not echo.value():
if time() > timeout:
print("Timeout: No pulse start detected.")
return -1 # Timeout if no pulse received
pulse_start = time()
while echo.value():
if time() > timeout:
print("Timeout: No pulse end detected.")
return -1 # Timeout if no pulse end received
pulse_end = time()
pulse_duration = pulse_end - pulse_start
distance = (pulse_duration * 34300) / 2 # Distance in cm
return distance
def main():
print("Starting main loop...")
if not connect_wifi():
print("Proceeding without Wi-Fi connection.")
return
while True:
distance = get_distance() # Get distance from ultrasonic sensor
if distance == -1:
lcd.clear()
lcd.putstr("Sensor Timeout!")
print("Sensor Timeout!")
continue
lcd.clear()
lcd.putstr(f"Distance: {distance:.2f} cm")
print(f"Distance: {distance:.2f} cm")
if distance < 100: # Threshold for vehicle detection (if the vehicle is within 1 meter)
lcd.clear()
lcd.putstr("No Parking Available!")
update_adafruit("Occupied")
print("Parking Status: Occupied")
# Ask for OTP to open the gate
lcd.putstr("\nEnter OTP: ")
otp = get_otp() # Get OTP from keypad
if otp == "1234": # Correct OTP
lcd.clear()
lcd.putstr("Access Granted!")
servo.duty_u16(7500) # Open gate
sleep(5)
servo.duty_u16(2500) # Close gate
else:
lcd.clear()
lcd.putstr("Wrong OTP!")
sleep(2)
else:
lcd.clear()
lcd.putstr("Parking Available!")
update_adafruit("Available")
print("Parking Status: Available")
sleep(1)
# Run the System
print("Starting system...")
main()