rhandycan1

PYTHON_ESP32_4SERVO_ROBOT

Aug 3rd, 2025 (edited)
179
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.88 KB | Source Code | 0 0
  1. '''PROGRAM BY: RANDY N. CAÑADA
  2. SUBSCRIBE: FB PAGES:
  3. Playlist.ph:
  4. https://www.facebook.com/profile.php?id=61573177858722
  5.  
  6. Arduino:
  7. https://www.facebook.com/rhacan2?__tn__=R
  8.  
  9. YOUTUBE:
  10. PlaylistPH
  11. https://www.youtube.com/@PlaylistPh-h2v
  12.  
  13. ElectroCrafters:
  14. https://www.youtube.com/channel/UCu1aqzUdTqSnTN5BHNlbVgA'''
  15.  
  16.  
  17.  
  18. from inputs import get_gamepad
  19. import socket
  20. import time
  21.  
  22. # 🧠 Replace with your ESP32's actual IP address
  23. ESP32_IP = '' # <<<< PUT YOUR ESP32 IP ADDRESS HERE
  24. PORT = 1234
  25.  
  26. def connect_socket():
  27.     while True:
  28.         try:
  29.             sock = socket.socket()
  30.             sock.connect((ESP32_IP, PORT))
  31.             print("✅ Connected to ESP32 over Wi-Fi")
  32.             return sock
  33.         except Exception as e:
  34.             print(f"🔌 Failed to connect: {e}")
  35.             print("🔄 Retrying in 3 seconds...")
  36.             time.sleep(3)
  37. sock = connect_socket()
  38.  
  39. try:
  40.     while True:
  41.         events = get_gamepad()
  42.         for event in events:
  43.             # 🔍 Show all incoming gamepad signals (great for mapping new buttons)
  44.             print(f"Code: {event.code} | Type: {event.ev_type} | State: {event.state}")
  45.  
  46.             # 🎯 Only respond to key/button press events
  47.             if event.ev_type == 'Key' and event.state == 1:
  48.                 msg = f"BTN:{event.code}\n"
  49.                 try:
  50.                     sock.sendall(msg.encode())
  51.                     print(f"📤 Sent → {msg.strip()}")
  52.                     time.sleep(0.05)  # 💤 Prevent flooding the ESP32
  53.                 except Exception as e:
  54.                     print(f"⚠️ Connection lost: {e}")
  55.                     print("🔁 Reconnecting...")
  56.                     sock.close()
  57.                     sock = connect_socket()
  58.                     break  # Restart the loop after reconnect
  59. except KeyboardInterrupt:
  60.     print("👋 Bridge manually stopped.")
  61.     sock.close()
  62.  
Tags: python
Advertisement
Add Comment
Please, Sign In to add comment