[原创] web控制led for esp8266

youxinweizhi   2018-7-20 11:16 楼主
好久不发帖了,趁感冒发烧无心工作,来一发。 直接奔入主题: 下面是main.py
  1. from machine import Pin
  2. import socket
  3. def webserver():
  4. global s ,red_stat,bai_stat,green_stat
  5. s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
  6. s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
  7. s.bind((wlan.ifconfig()[0],80))
  8. s.listen(1)
  9. while True:
  10. conn,addr = s.accept()
  11. request = conn.recv(1024)
  12. request = str(request)
  13. ib = request.find("Val=")
  14. if ib >0:
  15. ie = request.find(" ",ib)
  16. val = request[ib+4:ie]
  17. if val =="1":
  18. if red.value()==0:
  19. red.value(1)
  20. else:
  21. red.value(0)
  22. print("1")
  23. elif val =="2":
  24. if bai.value()==0:
  25. bai.value(1)
  26. else:
  27. bai.value(0)
  28. print("2")
  29. elif val=="3":
  30. if green.value()==0:
  31. green.value(1)
  32. else:
  33. green.value(0)
  34. print("3")
  35. conn.send(val.encode())
  36. else:
  37. with open('index.html',"r") as html:
  38. conn.sendall(html.read())
  39. conn.sendall("\r\n")
  40. conn.close()
  41. def connectWifi(ssid='xxxx',passwd='xxxxx'):
  42. global wlan
  43. wlan=network.WLAN(network.STA_IF)
  44. wlan.active(True)
  45. wlan.disconnect()
  46. wlan.connect(ssid,passwd)
  47. while(wlan.ifconfig()[0]=='0.0.0.0'):
  48. time.sleep(1)
  49. return True
  50. try:
  51. red = Pin(25,Pin.OUT)
  52. bai = Pin(14,Pin.OUT)
  53. green = Pin(12,Pin.OUT)
  54. connectWifi()
  55. webserver()
  56. except:
  57. if (s):
  58. s.close()
  59. wlan.disconnect()
  60. wlan.active(False)
下面是index.html
  1. <html>
  2. <head>
  3. <title>WebCtrl</title>
  4. <style type="text/css" id="style">
  5. .b{
  6. width: 100px;
  7. height: 100px;
  8. }
  9. </style>
  10. <script language="javascript">
  11. function dimSet(evt) {
  12. var me, he;
  13. var resp, xmlhttp=new XMLHttpRequest();
  14. me = evt.target;
  15. xmlhttp.open("GET","Val=" + me.value,true); xmlhttp.send()
  16. }
  17. </script>
  18. </head>
  19. <body>
  20. <h1>LED --- Web Control for Esp8266</h1>
  21. <div>
  22. <input class="b" type="button" value="1">
  23. <input class="b" type="button" value="2">
  24. <input class="b" type="button" value="3">
  25. <input class="b" type="button" value="4">
  26. <input class="b" type="button" value="5">
  27. </div>
  28. </body>
  29. </html>
此内容由EEWORLD论坛网友youxinweizhi原创,如需转载或用于商业用途需征得作者同意并注明出处 本帖最后由 youxinweizhi 于 2018-7-20 11:19 编辑

回复评论 (1)

感冒了多喝水,注意休息哦~~谢谢楼主的分享~~
玩板看这里: https://bbs.eeworld.com.cn/elecplay.html EEWorld测评频道众多好板等你来玩,还可以来频道许愿树许愿说说你想要玩的板子,我们都在努力为大家实现!
点赞  2018-7-20 14:49
电子工程世界版权所有 京B2-20211791 京ICP备10001474号-1 京公网安备 11010802033920号
    写回复