Advertisement
usa38

Pico Proximity Sensor (LED Alert + POST request to API)

Apr 25th, 2024 (edited)
432
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.20 KB | None | 0 0
  1. import machine
  2. import network
  3. import urequests as requests
  4. import time
  5. import bluetooth
  6.  
  7. # Define the onboard LED (you can choose any GPIO pin)
  8. led_onboard = machine.Pin("LED", machine.Pin.OUT)
  9.  
  10. # Initialize WiFi
  11. wlan = network.WLAN(network.STA_IF)
  12. wlan.active(True)
  13. wlan.connect('your_wifi_ssid', 'your_wifi_password')
  14.  
  15. # Wait for connection or fail
  16. max_wait = 10
  17. while max_wait > 0:
  18.     if wlan.status() < 0 or wlan.status() >= 3:
  19.         break
  20.     max_wait -= 1
  21.     print('Waiting for WiFi connection...')
  22.     time.sleep(1)
  23.  
  24. if wlan.status() != 3:
  25.     raise RuntimeError('Network connection failed')
  26. else:
  27.     print('Connected to WiFi')
  28.     status = wlan.ifconfig()
  29.     print('IP address:', status[0])
  30.  
  31. # Initialize Bluetooth
  32. ble = bluetooth.BLE()
  33.  
  34. # Callback when a central device (e.g., smartphone) connects
  35. def on_connect(event, data):
  36.     conn_handle, _, _ = data
  37.     print("Connected to device:", conn_handle)
  38.     led_onboard.on()  # Turn on the LED
  39.  
  40. # Callback when a central device disconnects
  41. def on_disconnect(event, data):
  42.     conn_handle, _, _ = data
  43.     print("Disconnected from device:", conn_handle)
  44.     led_onboard.off()  # Turn off the LED
  45.  
  46. # Set up BLE callbacks
  47. ble.irq(handler=on_connect, event=bluetooth.IRQ_CENTRAL_CONNECT)
  48. ble.irq(handler=on_disconnect, event=bluetooth.IRQ_CENTRAL_DISCONNECT)
  49.  
  50. # Start advertising (make the Pico discoverable)
  51. ble.gap_advertise(interval_us=500000, adv_data=b"\x02\x01\x06\x03\x03\x09\x18")
  52.  
  53. # Callback function to send POST request
  54. def send_post_request(timer):
  55.     timestamp = machine.RTC().datetime()
  56.     timestring = "%04d-%02d-%02d %02d:%02d:%02d" % (timestamp[0:3] + timestamp[4:7])
  57.     api_endpoint = "https://your.api.endpoint.com/data"  # Replace with your API URL
  58.     payload = {"timestamp": timestring, "event": "proximity_detected"}
  59.     try:
  60.         response = requests.post(api_endpoint, json=payload)
  61.         print(timestring, "Status Code:", response.status_code)
  62.         response.close()
  63.     except Exception as e:
  64.         print("Error sending POST request:", e)
  65.  
  66. # Initialize timer for periodic API requests
  67. timer = machine.Timer()
  68. timer.init(period=10000, mode=machine.Timer.PERIODIC, callback=send_post_request)
  69.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement