import machine
import time
import network
from umqtt.simple import MQTTClient
import urequests
wifi_ssid = "Your_WiFi_SSID"
wifi_password = "Your_WiFi_Password"
netpie_appid = "39a82fde-230c-4d79-8070-a0f0db7f2199"
netpie_key = "YToqajuqjMFDqQSQC8c5ajCCiMQDQYPR"
netpie_secret = "ue6UB7v1aZoWc9aGFEVcC7DHTpBfjs8o"
mqtt_server = "hcrs04.py"
mqtt_server2 = "__init__.py"
mqtt_port = 1883
mqtt_user = netpie_key
mqtt_pass = netpie_secret
rest_api_url = "https://api.netpie.io/v2/device/{0}/{1}".format(netpie_key, netpie_secret)
def send_data_to_netpie_mqtt(data):
c = MQTTClient(netpie_key, mqtt_server,mqtt_server2, user=mqtt_user, password=mqtt_pass)
c.connect()
c.publish("/app/{0}/out".format(netpie_appid), data)
c.disconnect()
def send_data_to_netpie_rest_api(data):
headers = {'Content-Type': 'application/json'}
data = '{"data":"' + data + '"}'
response = urequests.post(rest_api_url, data=data, headers=headers)
response.close()
# สั่งให้ MicroPython เชื่อมต่อ WiFi
connect_wifi()
# กำหนดขา Trig และ Echo
trig_pin = machine.Pin(13, machine.Pin.OUT)
echo_pin = machine.Pin(12, machine.Pin.IN)
# กำหนดขาสำหรับ Buzzer
buzzer_pin = machine.Pin(14, machine.Pin.OUT)
# กำหนดค่า PWM สำหรับ Buzzer
buzzer_pwm = machine.PWM(buzzer_pin, freq=1000, duty=0)
# กำหนดขาของ LED
led1 = machine.Pin(4, machine.Pin.OUT)
led2 = machine.Pin(5, machine.Pin.OUT)
led3 = machine.Pin(2, machine.Pin.OUT)
def distance_measurement():
# ส่งสัญญาณสั้นจาก Trig
trig_pin.on()
time.sleep_us(10)
trig_pin.off()
# รอรับสัญญาณจาก Echo
while echo_pin.value() == 0:
pulse_start = time.ticks_us()
while echo_pin.value() == 1:
pulse_end = time.ticks_us()
# คำนวณระยะที่วัดได้
pulse_duration = time.ticks_diff(pulse_end, pulse_start)
distance = (pulse_duration * 0.0343) / 2
return distance
while True:
dist = distance_measurement()
if dist < 10:
# ถ้าระยะน้อยกว่า 10 เซนติเมตรให้เปิด LED ทุกตัว
led1.on()
led2.off()
led3.off()
# ส่งเสียง beep 0.4 วินาที
buzzer_pwm.duty(512)
time.sleep(3)
buzzer_pwm.duty(0)
elif dist < 50:
led1.off()
led2.off()
led3.off()
led1.on()
# ส่งเสียง beep 0.4 วินาที
buzzer_pwm.duty(512)
time.sleep(0.4)
buzzer_pwm.duty(0)
elif dist < 100:
led1.off()
led2.off()
led3.off()
led2.on()
# ส่งเสียง beep 0.6 วินาที
buzzer_pwm.duty(512)
time.sleep(0.6)
buzzer_pwm.duty(0)
elif dist < 150:
led1.off()
led2.off()
led3.off()
led3.on()
# ส่งเสียง beep 0.8 วินาที
buzzer_pwm.duty(512)
time.sleep(0.8)
buzzer_pwm.duty(0)
elif dist < 200:
led1.off()
led2.off()
led3.off()
# ส่งเสียง beep 1 วินาที
buzzer_pwm.duty(512)
time.sleep(1.0)
buzzer_pwm.duty(0)
else:
led1.off()
led2.off()
led3.off()
time.sleep(0.1)