本帖最后由 豆爸 于 2023-12-19 01:34 编辑  
 
FireBeetle 2 ESP32-S3具有WIFI功能,以下示例使用ESP32-S3创建了一个wifi服务器,使用客户端连接到该服务器,控制LED的亮灭 
 
			
			
			- ''' 
 - 步骤:
 - 1.连接到WIFI”ESP32-S3“,已设置WIFI密码:12345678
 - 访问网址 http://192.168.4.1/ON 来打开灯 访问 http://192.168.4.1/OFF 来关闭灯
 - 3.在访问后通过点击开灯、关灯按钮来便捷控制灯的亮灭
 - '''
 - import usocket as socket
 - import network
 - from machine import Pin
 - 
 - ap_ssid = "ESP32-S3"
 - ap_password = "12345678"
 - ap_authmode = 3  # WPA2 PSK
 -  
 - 
 - wlan_ap = network.WLAN(network.AP_IF)
 - wlan_ap.active(True)
 - wlan_ap.config(essid=ap_ssid, password=ap_password, authmode=ap_authmode)
 - 
 - led = Pin(21, Pin.OUT)
 - 
 - def web_page():
 -     
 -     if led.value():
 -         gpio_state="ON"
 -     else:
 -         gpio_state="OFF"
 -   
 -     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">
 -   <link rel="icon" href="data:,"> <style>html{font-family: Helvetica; display:inline-block; margin: 0px auto; text-align: center;}
 -   h1{color: #0F3376; padding: 2vh;}p{font-size: 1.5rem;}.button{display: inline-block; background-color: #e7bd3b; border: none; 
 -   border-radius: 4px; color: white; padding: 16px 40px; text-decoration: none; font-size: 30px; margin: 2px; cursor: pointer;}
 -   .button2{background-color: #4286f4;}</style></head><body> <h1><font color="red">FireBeetle 2 ESP32-S3网页控制界面</font></h1> 
 -   <p>GPIO21 state: <strong>""" + gpio_state + """</strong></p><p><a href="/?led=on"><button class="button">开灯</button></a></p>
 -   <p><a href="/?led=off"><button class="button button2">关灯</button></a></p></body></html>"""
 -     return html
 - 
 - addr = socket.getaddrinfo('192.168.4.1', 80)[0][-1]
 - s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 - s.bind(('', 80))
 - s.listen(5)
 - 
 - while True:
 -   conn, addr = s.accept()
 -   print('Got a connection from %s' % str(addr))
 -   request = conn.recv(1024)
 -   request = str(request)
 -   print('Content = %s' % request)
 -   led_on = request.find('/?led=on')
 -   led_off = request.find('/?led=off')
 -   if led_on == 6:
 -     print('LED ON=',led_on)
 -     led.value(1)
 -   if led_off == 6:
 -     print('LED OFF=',led_off)
 -     led.value(0)
 -   response = web_page()
 -   conn.send('HTTP/1.1 200 OK\n')
 -   conn.send('Content-Type: text/html\n')
 -   conn.send('Connection: close\n\n')
 -   conn.sendall(response)
 -   conn.close()
 - 
 - 
 
  复制代码
  
 
 |