print("SOCIAL DISTANCING DETECTOR SYSTEM")
print("BY: DANIAL HAFIZ")
print("DATE: 1/9/2024")
# Import necessary libraries
from machine import Pin, PWM, SoftI2C
from utime import sleep
import Ultrasonic_library # Assumed to contain the HCSR04 class
import Oled_library # Assumed to contain SSD1306_I2C
# Define pins
TRIG_PIN = 5
ECHO_PIN = 18
LED_PIN = 23
BUZZER_PIN = 25
DISTANCE_THRESHOLD = 200 # Distance threshold in cm (2 meters)
# Initialize pins
led = Pin(LED_PIN, Pin.OUT)
# Initialize PWM for buzzer
buzzer = PWM(Pin(BUZZER_PIN))
# Initialize I2C for OLED (Adjust GPIOs if needed)
i2c = SoftI2C(scl=Pin(22), sda=Pin(21))
oled_width = 128
oled_height = 64
oled = Oled_library.SSD1306_I2C(oled_width, oled_height, i2c)
# Initialize the ultrasonic sensor
ultrasonic_sensor = Ultrasonic_library.HCSR04(trigger_pin=TRIG_PIN, echo_pin=ECHO_PIN)
def display_distance_on_oled(distance):
# Clear the display
oled.fill(0)
oled.text("Distance: {} cm".format(int(distance)), 0, 0)
if distance < DISTANCE_THRESHOLD:
oled.text("Alert: Too Close!", 0, 30)
else:
oled.text("Safe Distance", 0, 30)
oled.show()
def alert(distance):
if distance < DISTANCE_THRESHOLD:
led.on()
# Set the frequency to 4000 Hz for a loud sound
buzzer.freq(4000)
# Set duty cycle to 512 (50%) for audible sound
buzzer.duty(512)
else:
led.off()
# Turn off the buzzer by setting the duty cycle to 0
buzzer.duty(0)
# Main loop
while True:
# Measure the distance
distance = ultrasonic_sensor.distance_cm()
# Display the distance on the OLED
display_distance_on_oled(distance)
# Check distance and trigger alerts if necessary
alert(distance)
# Small delay between measurements
sleep(0.5)