from machine import Pin, PWM
import time
import urequests  # HTTP client for MicroPython

# Define pins for ultrasonic sensor
trig_pin = Pin(16, Pin.OUT)
echo_pin = Pin(17, Pin.IN)

# Define pin for buzzer
buzzer_pin = Pin(4, Pin.OUT)
buzzer_pwm = PWM(buzzer_pin)
buzzer_pwm.freq(500)  # Set PWM frequency

# ThingSpeak API endpoint and API key
THINGSPEAK_URL = "GET https://api.thingspeak.com/update?api_key=RU9WMUQNNF0CQRJK&field1=0"
THINGSPEAK_API_KEY = "RU9WMUQNNF0CQRJK"

def measure_distance():
    # Send a 10us pulse to trigger the ultrasonic sensor
    trig_pin.value(1)
    time.sleep_us(10)
    trig_pin.value(0)

    # Wait for echo pin to go high and then low
    while echo_pin.value() == 0:
        pulse_start = time.ticks_us()
    while echo_pin.value() == 1:
        pulse_end = time.ticks_us()

    # Calculate duration of echo pulse
    pulse_duration = time.ticks_diff(pulse_end, pulse_start)

    # Convert pulse duration to distance in centimeters
    distance = pulse_duration * 0.034 / 2

    return distance

def activate_buzzer():
    buzzer_pwm.duty(512)  # 50% duty cycle
    time.sleep(1)
    buzzer_pwm.duty(0)  # Turn off the buzzer

def send_to_thingspeak(distance):
    # Prepare data to send to ThingSpeak
    data = {"api_key": THINGSPEAK_API_KEY, "field1": str(distance)}

    # Send HTTP POST request to ThingSpeak API
    response = urequests.post(THINGSPEAK_URL, json=data)
    print("ThingSpeak response:", response.text)
    response.close()

try:
    while True:
        distance = measure_distance()
        print("Distance:", distance, "cm")

        # Send distance data to ThingSpeak
        send_to_thingspeak(distance)

        if distance < 10:  # If an object is closer than 10cm
            activate_buzzer()

        time.sleep(0.5)  # Wait for a short time before next measurement

except KeyboardInterrupt:
    # Clean up GPIO pins
    trig_pin.deinit()
    echo_pin.deinit()
    buzzer_pin.deinit()
Loading
esp32-devkit-c-v4
Loading
ssd1306