Breaking the Fourth Wall: Using Python Web Services to Control Arduino Microcontrollers
Joseph Mosby
@josephmosby
Poor man's schematics
YOU WILL NEED
Grokking the Arduino
Arduino code goals
  • Initialize a listener on the serial port
  • Read incoming serial data
  • Turn a light on and off depending on the serial byte received
Arduino code

(C, not Python)

void setup() {
  Serial.begin(9600);
}

void loop() {
  if (Serial.available() > 0) {
     char inByte = Serial.read();
  }

  if (inByte == '1') {
     digitalWrite(1, HIGH);
  }

  else if (inByte == '0') {
     digitalWrite(1, LOW);
  }
}
Python code, round 1
import serial

ser = serial.Serial('/dev/ttyACM0', 9600)

def turn_on():
  ser.write(b'1')
  return ""

def turn_off():
  ser.write(b'0')
  return ""
find your USB serial device
ls /dev

Will probably be something like ttyACM0 or ttyACM1.

Build out the Flask app
# views.py

from flask import Response, send_file
from app import app
import serial

ser = serial.Serial('/dev/ttyACM0', 9600)

@app.route('/', methods=['GET'])
def index():
   return send_file('index.html')

@app.route('/on', methods=['POST'])
def turn_on():
  ser.write(b'1')
  return ""

@app.route('/off', methods=['POST'])
def turn_off():
  ser.write(b'0')
  return ""

# __init__.py

from flask import Flask
app = Flask(__name__)

from app import views

# wsgihandler.py

import sys
sys.path.append('/home/www-data/sardine')
sys.path.append('/home/www-data/sardine/app')

from app import app as application # because WSGI is weird
Apache configuration
<VirtualHost *>

ServerName sardine
DocumentRoot /home/www-data/sardine
WSGIDaemonProcess sardine user=sardine group=sardine threads=5
WSGIScriptAlias / /home/www-data/sardine/wsgihandler.py

</VirtualHost>
questions?

/

#