from machine import Pin, PWM, I2C
from ssd1306 import SSD1306_I2C
import time
import urequests as ureq
import network
# Thiết lập chân GPIO cho cảm biến siêu âm HC-SR04 và LED
trig_pin = Pin(12, Pin.OUT) # Chân trig của HC-SR04
echo_pin = Pin(14, Pin.IN) # Chân echo của HC-SR04
led = Pin(13, Pin.OUT) # LED trên ESP32
# Thiết lập giao tiếp I2C cho màn hình OLED
i2c = I2C(0, scl=Pin(22), sda=Pin(21))
oled = SSD1306_I2C(128, 64, i2c)
# Thiết lập thông tin Wi-Fi và URL của Firebase
wifi_essid = 'Wokwi-GUEST'
wifi_pass = ''
urlFireBase = "https://test01-d8bc9-default-rtdb.asia-southeast1.firebasedatabase.app/"
# Kết nối WiFi
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if not wlan.isconnected():
print('Đang kết nối WiFi...')
wlan.connect(wifi_essid, wifi_pass)
while not wlan.isconnected():
pass
print('Đã kết nối:', wlan.ifconfig())
# Hàm đo khoảng cách sử dụng cảm biến siêu âm
def measure_distance():
trig_pin.off() # Tắt chân trig
time.sleep_us(2)
trig_pin.on() # Phát xung từ chân trig
time.sleep_us(5) # Xung có độ dài 5 micro giây
trig_pin.off() # Tắt chân trig
# Đo thời gian mà chân echo giữ ở mức HIGH
while echo_pin.value() == 0:
pulse_start = time.ticks_us()
while echo_pin.value() == 1:
pulse_end = time.ticks_us()
pulse_duration = pulse_end - pulse_start
# Tính khoảng cách dựa trên thời gian đo được
distance_cm = pulse_duration / 2 / 29.412
return distance_cm
# Hàm đẩy dữ liệu lên Firebase
def push_data(distance):
data = {'/hcsr04/distance': distance}
req = ureq.put(urlFireBase, json=data)
req.close()
# Kết nối WiFi khi bắt đầu chương trình
connect_wifi()
# Vòng lặp chính của chương trình
while True:
distance = measure_distance()
# Hiển thị giá trị lên màn hình OLED
oled.fill(0)
oled.text("Distance:", 0, 0)
oled.text("{:.2f}cm".format(distance), 0, 20)
oled.show()
# In kết quả ra Console (chỉ dùng để debug, không cần thiết khi sử dụng thực tế)
print("Distance:", distance, "cm")
# Đẩy khoảng cách lên Firebase
push_data(distance)
time.sleep(2) # Delay để tránh việc đo liên tục quá nhanh