【Micropython esp32/8266】网页点灯控制示例

【Micropython esp32/8266】网页点灯控制示例


  • ✨本示例基于Arduino框架下开发。✨

  • ⏳演示界面
    【Micropython esp32/8266】网页点灯控制示例_第1张图片

  • 本示例不依赖第三模块导入。

⛳程序导入方法

boot.pymain.py文件保存到micropython设备上即可运行。需要在boot.py文件中填写WiFi信息,其余无需做任何修改。

  • boot.py

该文件在设备中默认是存在的,可以直接打开设备中的这个文件,然后复制粘贴进去,进行覆盖操作,注意填写自己的WiFi信息,并保存。

【Micropython esp32/8266】网页点灯控制示例_第2张图片


# This file is executed on every boot (including wake-boot from deepsleep)
#import esp
#esp.osdebug(None)
#import uos, machine
#uos.dupterm(None, 1) # disable REPL on UART(0)
#import gc
#import webrepl
#webrepl.start()
#gc.collect()

try:
  import usocket as socket
except:
  import socket

from machine import Pin
import network

import esp
esp.osdebug(None)

import gc
gc.collect()
# wifi信息
ssid = 'WiFi账号'
password = 'WiFi密码'

station = network.WLAN(network.STA_IF)

station.active(True)
station.connect(ssid, password)

while station.isconnected() == False:
  pass

print('Connection successful')
print(station.ifconfig())

led = Pin(2, Pin.OUT)

  • main.py

将main.py文件保存到设备上后,需要重启设备才能运行。

def web_page():
  if led.value():
    gpio_state="OFF"
  else:
    gpio_state="ON"
  
  html = """-8"> ESP32/8266网页控制界面 " 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()

  • Shell调试窗口打印信息

【Micropython esp32/8266】网页点灯控制示例_第3张图片

你可能感兴趣的:(#,MicroPython,for,ESP32,#,MicroPython,for,ESP8266,MicroPython,网页控制,esp32/8266)