天天看點

【Micropython esp32/8266】AP模式下網頁點燈控制示例

【Micropython esp32/8266】AP模式下網頁點燈控制示例

  • 📍相關篇《【Micropython esp32/8266】網頁點燈控制示例》
    【Micropython esp32/8266】AP模式下網頁點燈控制示例
⛳#### 前面一篇是關于STA模式下網頁控制,本次帶來的是

Micropython

裝置作為

AP

模式下,去通路裝置,并控制點燈程式。

🎯建立AP模式

ap_ssid = "ESP8266AP"# 熱點信号名稱
ap_password = "12345678"#密碼
ap_authmode = 3  # 加密方式;WPA2
 
wlan_ap = network.WLAN(network.AP_IF)
wlan_ap.active(True)
wlan_ap.config(essid=ap_ssid, password=ap_password, authmode=ap_authmode)
           

📝主程式代碼

'''
    authmode模式:
  AUTH_OPEN -- 0
  AUTH_WEP -- 1
  AUTH_WPA_PSK -- 2
  AUTH_WPA2_PSK -- 3
  AUTH_WPA_WPA2_PSK -- 4
'''
import usocket as socket
import network
from machine import Pin
ap_ssid = "ESP8266AP"
ap_password = "12345678"
ap_authmode = 3  # WPA2
 

wlan_ap = network.WLAN(network.AP_IF)

wlan_ap.active(True)
wlan_ap.config(essid=ap_ssid, password=ap_password, authmode=ap_authmode)

print('Connect to WiFi ssid ' + ap_ssid + ', default password: ' + ap_password)
print('and access the ESP via your favorite web browser at 192.168.4.1.')
#print('Listening on:', addr)

led = Pin(2, Pin.OUT)

def web_page():
  if led.value():
    gpio_state="OFF"
  else:
    gpio_state="ON"
  
  html = """<html><meta charset="UTF-8"><head> <title>ESP32/8266網頁控制界面(AP模式)</title> <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">ESP32/8266網頁控制界面</font></h1> 
  <p>GPIO state: <strong>""" + gpio_state + """</strong></p><p><a href="/?led=on"><button class="button">ON</button></a></p>
  <p><a href="/?led=off"><button class="button button2">OFF</button></a></p></body></html>"""
  return html

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.value(0)
  if led_off == 6:
    print('LED OFF')
    led.value(1)
  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()

           

⛳連接配接和通路

📍程式運作後,通過電腦或手機連接配接micropython裝置的WiFi。

【Micropython esp32/8266】AP模式下網頁點燈控制示例
  • 📌Shell調試視窗将列印被連接配接上的裝置IP位址
    【Micropython esp32/8266】AP模式下網頁點燈控制示例
  • 接下來解釋通過浏覽器通路micropython裝置網關位址,進行裝置引腳控制。
    【Micropython esp32/8266】AP模式下網頁點燈控制示例

繼續閱讀