2023-12-19 01:34:32 [显示全部楼层]
1076浏览
查看: 1076|回复: 0

[ESP8266/ESP32] FireBeetle 2 ESP32-S3 WIFI控制LED(MicroPython)

[复制链接]
本帖最后由 豆爸 于 2023-12-19 01:34 编辑

FireBeetle 2 ESP32-S3具有WIFI功能,以下示例使用ESP32-S3创建了一个wifi服务器,使用客户端连接到该服务器,控制LED的亮灭

  1. '''
  2. 步骤:
  3. 1.连接到WIFI”ESP32-S3“,已设置WIFI密码:12345678
  4. 访问网址 http://192.168.4.1/ON 来打开灯 访问 http://192.168.4.1/OFF 来关闭灯
  5. 3.在访问后通过点击开灯、关灯按钮来便捷控制灯的亮灭
  6. '''
  7. import usocket as socket
  8. import network
  9. from machine import Pin
  10. ap_ssid = "ESP32-S3"
  11. ap_password = "12345678"
  12. ap_authmode = 3  # WPA2 PSK
  13. wlan_ap = network.WLAN(network.AP_IF)
  14. wlan_ap.active(True)
  15. wlan_ap.config(essid=ap_ssid, password=ap_password, authmode=ap_authmode)
  16. led = Pin(21, Pin.OUT)
  17. def web_page():
  18.    
  19.     if led.value():
  20.         gpio_state="ON"
  21.     else:
  22.         gpio_state="OFF"
  23.   
  24.     html = """<!DOCTYPE html><html><meta charset="UTF-8"><head><title>FireBeetle 2 ESP32-S3网页控制界面(AP模式)</title><style>body {text-align: center;} table {margin: auto;}</style><meta name="viewport" content="width=device-width, initial-scale=1">
  25.   <link rel="icon" href="data:,"> <style>html{font-family: Helvetica; display:inline-block; margin: 0px auto; text-align: center;}
  26.   h1{color: #0F3376; padding: 2vh;}p{font-size: 1.5rem;}.button{display: inline-block; background-color: #e7bd3b; border: none;
  27.   border-radius: 4px; color: white; padding: 16px 40px; text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}
  28.   .button2{background-color: #4286f4;}</style></head><body> <h1><font color="red">FireBeetle 2 ESP32-S3网页控制界面</font></h1>
  29.   <p>GPIO21 state: <strong>""" + gpio_state + """</strong></p><p><a href="/?led=on"><button class="button">开灯</button></a></p>
  30.   <p><a href="/?led=off"><button class="button button2">关灯</button></a></p></body></html>"""
  31.     return html
  32. addr = socket.getaddrinfo('192.168.4.1', 80)[0][-1]
  33. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  34. s.bind(('', 80))
  35. s.listen(5)
  36. while True:
  37.   conn, addr = s.accept()
  38.   print('Got a connection from %s' % str(addr))
  39.   request = conn.recv(1024)
  40.   request = str(request)
  41.   print('Content = %s' % request)
  42.   led_on = request.find('/?led=on')
  43.   led_off = request.find('/?led=off')
  44.   if led_on == 6:
  45.     print('LED ON=',led_on)
  46.     led.value(1)
  47.   if led_off == 6:
  48.     print('LED OFF=',led_off)
  49.     led.value(0)
  50.   response = web_page()
  51.   conn.send('HTTP/1.1 200 OK\n')
  52.   conn.send('Content-Type: text/html\n')
  53.   conn.send('Connection: close\n\n')
  54.   conn.sendall(response)
  55.   conn.close()
复制代码


您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

为本项目制作心愿单
购买心愿单
心愿单 编辑
[[wsData.name]]

硬件清单

  • [[d.name]]
btnicon
我也要做!
点击进入购买页面
上海智位机器人股份有限公司 沪ICP备09038501号-4

© 2013-2024 Comsenz Inc. Powered by Discuz! X3.4 Licensed

mail