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

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


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

  • ⏳演示界面
    在这里插入图片描述

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

⛳程序导入方法

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

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

在这里插入图片描述


# 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="ON"	#低电平点亮
  else:
    gpio_state="OFF"
  
  html = """<html><meta charset="UTF-8"><head> <title>ESP32/8266网页控制界面</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(1)
  if led_off == 6:
    print('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()

  • 📍Shell调试窗口打印信息

在这里插入图片描述

  • 2
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值