Created
July 19, 2016 01:18
-
-
Save infamy/5bccd620e2f697ac84cf864653e7a75f to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import network | |
import machine | |
import usocket as socket | |
import json | |
# Constants | |
SSID = "SSID" | |
PASSWORD = "PASSWORD" | |
html = """<!DOCTYPE html> | |
<html> | |
<head> <title>ESP8266 LED ON/OFF</title> </head> | |
<center><h2>A simple webserver for turning LED's on and off with Micropython</h2></center> | |
<center><h3>(for noobs to both the ESP8266 and Micropython)</h3></center> | |
<a href="/digital/2/0">On</a> <a href="/digital/2/1">Off</a> | |
</html> | |
""" | |
def connect(): | |
sta_if = network.WLAN(network.STA_IF) | |
if not sta_if.isconnected(): | |
print('trying to connect...') | |
sta_if.active(True) | |
sta_if.connect(SSID, PASSWORD) | |
while not sta_if.isconnected(): | |
pass | |
print('network config:'+str(sta_if.ifconfig())) | |
return sta_if.ifconfig()[0] | |
def server(ip): | |
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) | |
s.bind(('', 80)) | |
s.listen(5) | |
counter=0 | |
while True: | |
conn, addr = s.accept() | |
print("Got a connection from %s" % str(addr)) | |
request = conn.recv(1024) | |
print("Content = %s" % str(request)) | |
request = str(request) | |
print(request) | |
# request = str(request) | |
if request.startswith("b'GET /digital/"): | |
pin = int(request[15]) | |
value = int(request[17]) | |
led = machine.Pin(pin, machine.Pin.OUT, value=value) | |
reply = { | |
'message': ("Pin D%d set to %d" % (pin, value)), | |
'connected': True, | |
} | |
conn.send(json.dumps(reply)) | |
conn.close() | |
IP = connect() | |
print("Connected!") | |
server(IP) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment