This week, I made a web interface to control my Fabduino. The interface allowed me to taggle the onboard LED on and off from the web. To do this, I used PySerial and Python’s web microframework, Flask.

First, I created the Arduino code to make the Arduino listen for input over serial. The code (shown below) listens for a ‘1’ or a ‘0’ char to be sent over the serial. If it recieves a ‘1’, it turns the LED on by setting to voltage to HIGH. If it recives a ‘0’, it turns the LED off by setting the voltage to LOW.

toggle.ino

void setup() {
  Serial.begin(9600); // Set the baud rate
  pinMode(13, OUTPUT); // Set the onboard LED to output
  Serial.println("Ready");
}
void loop() {
  char toggle = ' ';
  if(Serial.available()){ // Only send data back if data has been sent
    char toggle = Serial.read(); // Read the incoming data
    if(toggle == '1'){
      digitalWrite(13, HIGH);   // Turn the LED on (HIGH is the voltage level)     
    }
    if(toggle == '0'){
      digitalWrite(13, LOW);	// Turn the LED off (LOW is the voltage level)    
    }
  }
  delay(100); // delay for 1/10 of a second
}

Next, I created the Python code to send the ‘1’ or ‘0’ to the serial. I used Flask to make a simple (2 button) webpage that, when clicked, submitted a post request with either the value ‘ON’ or ‘OFF’ to the application.

toggle.py

import serial
from time import sleep
from flask import request

from flask import Flask
app = Flask(__name__)

@app.route("/", methods = ['POST', 'GET'])
def hello():
	if request.method == 'POST':
		print request.form['submit']
		ser = serial.Serial('/dev/tty.usbserial-FTGS552S', 9600, timeout=1)
		if request.form['submit'] == 'ON':
			print '1'
			ser.write('1')
		elif request.form['submit'] == 'OFF':
			print '0'
			ser.write('0')
		else:
			pass # unknown
	return '<form action="/" method="POST"><input type="submit" name="submit" value="ON"><input type="submit" name="submit" value="OFF"></form>'

if __name__ == "__main__":
	app.run()

To run the program, first load the toggle.ino code onto the Fabduino. Next, run the python code using ‘python toggle.py’ and open up http://localhost:5000. Clicking the buttons on the screen turns the on-board LED on and off (:

Working Demo