import network,usocket
from machine import Pin,PWM,SoftI2C
import time
from ssd1306 import SSD1306_I2C
i2c = SoftI2C(sda=Pin(4), scl=Pin(5))
oled = SSD1306_I2C(128, 64, i2c, addr=0x3c)
led = Pin(2, Pin.OUT)
ssid = '...'
password = '...'
def WIFI_Connect():
WIFI_LED=led
global wlan
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
start_time=time.time()
if not wlan.isconnected():
wlan.connect(ssid, password)
while not wlan.isconnected():
WIFI_LED.value(1)
time.sleep_ms(300)
WIFI_LED.value(0)
time.sleep_ms(300)
if time.time()-start_time > 15 :
break
if wlan.isconnected():
WIFI_LED.value(1)
oled.fill(0)
oled.text('IP:'+ wlan.ifconfig()[0],0,38)
oled.show()
return True
else:
return False
if WIFI_Connect():
s = usocket.socket(usocket.AF_INET, usocket.SOCK_STREAM)
s.setsockopt(usocket.SOL_SOCKET, usocket.SO_REUSEADDR, 1)
s.bind(('', 80))
s.listen(5)
S1 = PWM(Pin(12), freq=50, duty=0)
S2 = PWM(Pin(13), freq=50, duty=0)
def Servo(servo,angle):
servo.duty(int(((angle+90)*2/180+0.5)/20*1023))
def web_page():
if led.value() == 1:
gpio_state = '打开'
else:
gpio_state = '关闭'
# html code ...
html = """<html><head><meta charset="UTF-8"><title>LEGO Robot Arm For Light</title> <meta name="viewport" content="width=device-width, initial-scale=1">
<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>LEGO Robot Arm For Light</h1>
<p>状态: <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
while True:
if wlan.isconnected():
conn, addr = s.accept()
req = conn.recv(1024)
req = str(req)
led_on = req.find('/?led=on')
led_off = req.find('/?led=off')
if led_on == 6:
led.value(1)
oled.fill_rect(0, 56, 128, 64, 0)
oled.text('Status:ON',0,56)
oled.show()
Servo(S2,70)
time.sleep_ms(500)
Servo(S1,20)
time.sleep_ms(500)
Servo(S1,50)
time.sleep_ms(500)
Servo(S2,-90)
elif led_off == 6:
led.value(0)
oled.fill_rect(0, 56, 128, 64, 0)
oled.text('Status:OFF',0,56)
oled.show()
Servo(S2,20)
time.sleep_ms(500)
Servo(S1,20)
time.sleep_ms(500)
Servo(S1,50)
time.sleep_ms(500)
Servo(S2,-90)
else:
pass
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()
else:
machine.reset()
运行后,只要在浏览器发送请求后,repl的连接就会断开,但是我并没有使用串口啊。板子是8266。还有一个问题是,如果运行过一会后,再在浏览器发送请求,会有延迟。
|