From ce7b32fb0427d5dcdd22150e9f6ead2eccfcbcb6 Mon Sep 17 00:00:00 2001 From: Rene Date: Mon, 23 Jun 2025 14:23:20 +0200 Subject: [PATCH] ESP32 WROOM finished 1.0 --- local_code/ESP32/app.py | 70 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 local_code/ESP32/app.py diff --git a/local_code/ESP32/app.py b/local_code/ESP32/app.py new file mode 100644 index 0000000..95bcdad --- /dev/null +++ b/local_code/ESP32/app.py @@ -0,0 +1,70 @@ +import requests +import network +import time +import machine + +# Set up GPIO (ESP32 pin numbers) +PIN = 2 # Change this to your actual ESP32 pin number + +# Set up Wi-Fi connection (if needed for sending HTTP requests) +ssid = 'ReCa_2G' +password = 'mosfet9843' + +def send_message(): + try: + + # Initialize station interface + station = network.WLAN(network.STA_IF) + station.active(True) + station.config(reconnects = 5) + + # Check if already connected + if not station.isconnected(): + # Set mode to Station (client) + #station.mode(network.MODE_STATION) + + print('Connecting to WiFi...') + station.connect(ssid, password) + + # Wait for connection with a timeout + start_time = time.time() + while not station.isconnected() and (time.time() - start_time) < 10: + time.sleep(1) + + if not station.isconnected(): + raise Exception("Failed to connect to Wi-Fi") + + # Get IP address after successful connection + ip_address = station.ifconfig()[0] + print(f"Connected to {ssid}, IP Address: {ip_address}") + + # Send HTTP request + print("Sending message...") + response = requests.post( + 'http://192.168.178.171:5020/send', + json={'message': 'klingel geht'}, + headers={'Content-Type': 'application/json'} + ) + return f"Message sent with status code {response.status_code}" + except Exception as e: + print(f"Connection failed or error while sending message: {str(e)}") + machine.reset() + return None + +# Set up GPIO +pin = machine.Pin(PIN, machine.Pin.IN, machine.Pin.PULL_UP) + +try: + while True: + current_state = pin.value() + if current_state == 1: + print("GPIO Pin {} is HIGH".format(PIN)) + result = send_message() + print(result) + time.sleep(5) + time.sleep(0.5) # Check pin every 0,5 seconds +except KeyboardInterrupt: + print("\nProgram stopped by user") +finally: + pass # No need for GPIO cleanup in MicroPython +