ESP32 HC-SR04 Ultrasonic IFTTT

Cette page contient des modifications qui ne sont pas marquées pour la traduction.

Auteur avatarOmksabb | Dernière modification 14/01/2023 par Omksabb

This project will take data from an ultrasonic sensor, pass it through a Webhook, and publish the data in a Google Sheet.

Matériaux

Outils

Étape 1 - I will explain how to set up the IDE, the IFTTT, the circuit, and everything else in person. Refer to the code below:

Étape 2 - The code:


import machine
import time
import urequests
import network

# Wi-Fi credentials
ssid = 'wifi_name' #input your own wifi name
password = 'password' #input your own password

# IFTTT webhook key
api_key = 'your_own_key' #input your own key

# Connect to Wi-Fi
station = network.WLAN(network.STA_IF)
station.active(True)
station.connect(ssid, password)
while station.isconnected() == False:
    pass
print('Connection successful')
print(station.ifconfig())

# Set up ultrasonic sensor
trigger = machine.Pin(4, machine.Pin.OUT)
echo = machine.Pin(5, machine.Pin.IN)


def main():
    while True:
        # Send trigger pulse
        trigger.value(0)
        time.sleep_us(5)
        trigger.value(1)
        time.sleep_us(10)
        trigger.value(0)

        # Measure duration of echo pulse
        while echo.value() == 0:
            start = time.ticks_us()
        while echo.value() == 1:
            end = time.ticks_us()
        duration = time.ticks_diff(end, start)

        # Calculate distance
        distance = duration * 0.034 / 2
        

        # Send data to IFTTT
        data = {'value1': distance}
        submitData("ultrasonic_distance", data)


        # Delay before next measurement
        time.sleep(5)

def submitData(event, data):
    try:
        print('Sending data to IFTTT:', data)
        request_headers = {'Content-Type': 'application/json'}
        request = urequests.post(
            'https://maker.ifttt.com/trigger/'+ event + '/with/key/' + api_key,
            json=data,headers=request_headers)
        print(request.text)
        request.close()
    except OSError as e:
        print('Failed to send data to IFTTT.', e)
 
if __name__ == '__main__':
    main()

Commentaires

Published