print("Hello, ESP32!")
#import all necessary modules/libraries
import hcsr04 # Sensor Library
import ssd1306 # OLED Library
from utime import sleep
from machine import SoftI2C, Pin, PWM
import urequests # Library for HTTP requests
# Declare ultrasonic pin connection
ultrasonic_sensor = hcsr04.HCSR04(trigger_pin=12, echo_pin=14, echo_timeout_us=500 * 2 * 30)
# PIN Declaration for OLED
i2c_oleddisplay = SoftI2C(scl=Pin(22), sda=Pin(21))
oled_width = 128
oled_height = 64
oled = ssd1306.SSD1306_I2C(oled_width, oled_height, i2c_oleddisplay)
# Declare Buzzer Pin
buzzer = PWM(Pin(4), Pin.OUT)
# Declare LED Pins
LED_RED = Pin(25, Pin.OUT)
LED_GREEN = Pin(26, Pin.OUT)
LED_BLUE = Pin(27, Pin.OUT)
# WiFi and LINE Token
ssid = "Wokwi-GUEST"
password = ""
line_token = "k06MUJm9zbrlt9k9NXsyIPYY2IuIrCNiRn1yOMMJ54F"
# WiFi connection function
def connect_wifi():
from network import WLAN, STA_IF
wlan = WLAN(STA_IF)
wlan.active(True)
wlan.connect(ssid, password)
while not wlan.isconnected():
sleep(1)
print("Connected to WiFi:", wlan.ifconfig())
# Send LINE notification
def send_line_notify(message):
url = "https://notify-api.line.me/api/notify"
headers = {
"Authorization": "Bearer " + line_token,
"Content-Type": "application/x-www-form-urlencoded",
}
data = "message=" + message
try:
response = urequests.post(url, data=data, headers=headers)
response.close()
except Exception as e:
print("Error sending LINE notification:", e)
# Initialize WiFi
connect_wifi()
while True:
# Measure distance
object_detect_cm = ultrasonic_sensor.distance_cm()
object_detect_mm = ultrasonic_sensor.distance_mm()
# Display object distance on Serial Monitor
print("Distance from an object in cm :", object_detect_cm)
print("Distance from an object in mm :", object_detect_mm)
print("---------------------------------------------------\n")
# Display object distance on OLED Screen
oled.fill(0)
oled.text('Object Detected:', 0, 0, 1)
oled.text(str(object_detect_cm), 0, 20, 1)
oled.text('cm', 70, 20, 1)
oled.text(str(object_detect_mm), 0, 40, 1)
oled.text('mm', 70, 40, 1)
oled.show()
# LED Indicator for Distance
if object_detect_cm <= 10:
LED_RED.value(1)
LED_GREEN.value(0)
LED_BLUE.value(0)
# Buzzer alert
for i in range(5):
buzzer.init(freq=1000, duty=512)
sleep(0.5)
buzzer.init(freq=1, duty=0)
sleep(0.5)
send_line_notify("Warning! Object detected at 10 cm.")
elif 10 < object_detect_cm <= 20:
LED_RED.value(0)
LED_GREEN.value(1)
LED_BLUE.value(0)
send_line_notify("Object detected at 20 cm.")
elif 20 < object_detect_cm <= 30:
LED_RED.value(0)
LED_GREEN.value(0)
LED_BLUE.value(1)
send_line_notify("Object detected at 30 cm.")
else:
LED_RED.value(0)
LED_GREEN.value(0)
LED_BLUE.value(0)
# Sleep for 5 seconds before the next measurement
sleep(5)