Skip to content

Instantly share code, notes, and snippets.

@ShawnHymel
Last active March 14, 2019 21:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ShawnHymel/ff629f76e023f0fee2190601c2cddabb to your computer and use it in GitHub Desktop.
Save ShawnHymel/ff629f76e023f0fee2190601c2cddabb to your computer and use it in GitHub Desktop.
Toggle LED Web Server
import BaseHTTPServer
import SocketServer
import RPi.GPIO as GPIO
# LED pin number (GPIO)
LED = 2
# Port number for our server
PORT = 80
# Set up LED
led_state = 0
GPIO.setmode(GPIO.BCM)
GPIO.setup(LED, GPIO.OUT)
GPIO.output(LED, led_state)
# Handle GET requests
class Handler(BaseHTTPServer.BaseHTTPRequestHandler):
def do_GET(self):
global led_state
# If we get a "pressed" message, toggle LED
msg = self.path[1:]
if msg == 'pressed':
print("Toggling")
led_state = 1 - led_state
GPIO.output(LED, led_state)
# Always send index.html
f = open('index.html', 'rb')
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
self.wfile.write(f.read())
f.close()
return
# Attach handler to server
httpd = SocketServer.TCPServer(("", PORT), Handler)
# Start running server
print("Serving at port", PORT)
try:
httpd.serve_forever()
finally:
GPIO.cleanup()
<html>
<head>
<title>Yay Python!</title>
</head>
<body>
<h1>Toggle LED</h1>
<a href="pressed"><button>Push Me!</button></a>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment