uPyCraft-micropython教程--網頁控制板載LED燈
|
#===============WebLED.py
from machine import Pin,PWM
import network
import os
import time
import socket
import gc
SSID="PTS-2F"
PASSWORD=""
wlan=None
s=None
led=None
def connectWifi(ssid,passwd):
global wlan
wlan=network.WLAN(network.STA_IF)
wlan.active(True)
wlan.disconnect()
wlan.connect(ssid,passwd)
while(wlan.ifconfig()[0]=='0.0.0.0'):
time.sleep(1)
return True
def ajaxWebserv():
# minimal Ajax in Control Webserver
global s,led
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((wlan.ifconfig()[0], 80))
s.listen(1)
while True:
conn, addr = s.accept()
#print("Got a connection from %s" % str(addr))
request = conn.recv(1024)
conn.sendall('HTTP/1.1 200 OK\nConnection: close\nServer: FireBeetle\nContent-Type: text/html\n\n')
request = str(request)
ib = request.find('Val=')
if ib > 0 :
ie = request.find(' ', ib)
Val = request[ib+4:ie]
print("Val =", Val)
led.duty(int(Val)*100)
conn.send(Val)
else:
with open('webCtrl.htm', 'r') as html:
conn.sendall(html.read())
conn.sendall('\r\n')
conn.close()
#print("Connection wth %s closed" % str(addr))
try:
led=PWM(Pin(2),freq=100)
led.init()
led.duty(0)
connectWifi(SSID, PASSWORD)
ajaxWebserv()
except:
if (s):
s.close()
led.deinit()
wlan.disconnect()
wlan.active(False)
#======================webCtrl.htm===================
<html>
<head>
<title>ajaxWebCtrl</title>
<link rel="icon" href="data:;base64,=">
<style type="text/css" id="style">
.dimwrap { border: 2px solid red; height: 150px; width: 600px;}
.dimSlide { transform: scaleX(2) rotate(0deg); width: 256px;position: relative; top: 80px; left: 90px;}
.dimVal { width: 90px; height:30;position: relative; top: 20px; left: 20px}
</style>
<script language="javascript">
function dimSet(evt) {
var me, he;
var resp, xmlhttp=new XMLHttpRequest();
me = evt.target;
he = document.getElementById(me.id == "dimVal"? "dimSlide":"dimVal"); // need my other value node
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200){
resp = xmlhttp.responseText;
console.log(resp);
he.value = parseInt(resp);
}
}
xmlhttp.open("GET","Val=" + me.value,true); xmlhttp.send()
}
</script>
</head>
<body>
<h1>PWM LED --- Web Control for FireBeetle</h1>
<div class="dimwrap" id="dimwrap">
<input class="dimVal" type="number" id="dimVal" min="0" max="10" step="1" value="0" onclick="dimSet(event)" oninput="dimSet(event)" >
<input class= "dimSlide" type="range" id="dimSlide" min="0" max="10" step="1" value="0" onclick="dimSet(event)" oninput="dimSet(event)" >
</div>
</body>
</html>
沒有留言:
張貼留言