← Back to All Weeks
Week14

Week 14: Interface and Application Programming

A browser interface for an LED

I built a small application with ON and OFF buttons in a browser. A local Python Flask server receives the button requests and sends text commands over USB serial to the microcontroller. The firmware reads those commands and switches the LED on D1. This links a user action to an output on my board.

Group assignment: comparing interface tools

Our group compares Arduino Serial Monitor, Python with PySerial/Tkinter, Processing and Web Serial. The comparison considers setup, communication, interface design and the connection to hardware. A terminal is useful for testing commands directly, while an application can present controls that fit the task.

Our comparison is on our group assignment page. The individual application below uses Flask and PySerial, with a web page as its interface.

Interface structure and communication

The HTML page contains two forms that send POST requests to /on and /off. Flask writes ON or OFF to the serial port at 9600 baud, then renders the page with the acknowledgement or a useful error. The newline marks the end of each command.

The application runs on the computer connected to the board. This Fab Academy site hosts the documentation and downloads; the local Flask process provides the live controls. Opening the HTML file by itself does not create the serial connection.

The ON/OFF browser interface
The ON/OFF browser interface

Flask backend

The revised backend takes the actual port from LED_SERIAL_PORT; it does not assume COM10. It opens the port on the first command, so the page still loads when no board is configured. It waits for the firmware acknowledgement before reporting that the command was acknowledged. The home route loads templates/index.html, so the folder structure is part of the application.

"""Local LED control; revised with Codex assistance. Physical retest pending."""
import atexit
import os
import threading
import time
from urllib.parse import urlsplit
from pathlib import Path
from flask import Flask, render_template, request, abort
import serial

app = Flask(__name__, template_folder=str(Path(__file__).resolve().parent/'templates'))
app.config['MAX_CONTENT_LENGTH'] = 1024
app.config['LED_SERIAL_PORT'] = os.environ.get('LED_SERIAL_PORT', '').strip()
board = None
board_lock = threading.Lock()


def close_board():
    global board
    if board is not None:
        try:
            board.close()
        except (serial.SerialException, OSError):
            pass
        board = None


atexit.register(close_board)


@app.before_request
def local_request_only():
    if urlsplit(request.host_url).hostname not in {'localhost', '127.0.0.1'}:
        abort(400)
    if request.method == 'POST':
        origin = request.headers.get('Origin')
        if origin and origin.rstrip('/') != request.host_url.rstrip('/'):
            abort(403)
        if request.headers.get('Sec-Fetch-Site') == 'cross-site':
            abort(403)


def page(message=None, error=False, status=200):
    port = app.config['LED_SERIAL_PORT']
    if message is None:
        message = ('Ready to send a command. The current LED state is unknown.' if port
                   else 'Set LED_SERIAL_PORT to the connected board, then restart this local application.')
    return render_template('index.html', message=message, error=error, port=port), status


@app.route('/')
def home():
    return page()


def send_command(command):
    global board
    port = app.config['LED_SERIAL_PORT']
    if not port:
        return page('No serial port is configured. Set LED_SERIAL_PORT and restart.', True, 503)
    if not board_lock.acquire(blocking=False):
        return page('A command is still pending. Wait for its result before trying again.', True, 409)
    try:
        if board is None or not board.is_open:
            board = serial.Serial(port, 9600, timeout=0.25, write_timeout=1)
        board.reset_input_buffer()
        board.write((command+'\n').encode('ascii'))
        board.flush()
        expected = 'LED turned '+command
        deadline = time.monotonic()+2.5
        while time.monotonic() < deadline:
            reply = board.readline().decode('utf-8', errors='replace').strip()
            if reply == expected:
                return page('Board acknowledged the '+command+' command.')
        return page('The command was sent, but the board did not confirm it. Check the firmware and serial port, then retry.', True, 502)
    except (serial.SerialException, OSError):
        close_board()
        return page('The serial port could not be used. Check the board connection and close any other serial monitor, then retry.', True, 503)
    finally:
        board_lock.release()


@app.route('/on', methods=['POST'])
def led_on():
    return send_command('ON')


@app.route('/off', methods=['POST'])
def led_off():
    return send_command('OFF')


if __name__ == '__main__':
    app.run(host='127.0.0.1', port=5000, debug=False)
Installing the Python dependencies
Installing the Python dependencies
Checking the connected serial port
Checking the connected serial port
The Flask backend
The Flask backend

Microcontroller firmware

The firmware initializes serial at 9600 baud and sets D1 as an output. It reads a line, trims whitespace and compares the command with ON and OFF. Unknown text produces a diagnostic message without changing the output. I can use Serial Monitor to test this part independently, then close it before Flask opens the same port.

#define LED_PIN D1

void setup() {
  Serial.begin(9600);
  pinMode(LED_PIN, OUTPUT);
  Serial.println("Ready and waiting for commands...");
}

void loop() {
  if (Serial.available() > 0) {
    String command = Serial.readStringUntil('\n');
    command.trim();
    Serial.print("Received command: ");
    Serial.println(command);

    if (command == "ON") {
      digitalWrite(LED_PIN, HIGH);
      Serial.println("LED turned ON");
    } else if (command == "OFF") {
      digitalWrite(LED_PIN, LOW);
      Serial.println("LED turned OFF");
    } else {
      Serial.println("Unknown command");
    }
  }
}
The LED command sketch
The LED command sketch
Uploading the LED firmware
Uploading the LED firmware
Recorded LED test

Running the application

  • Extract the complete package and keep app.py, requirements.txt and the templates folder together.
  • Create a Python virtual environment and install the dependencies with python -m pip install -r requirements.txt.
  • Upload the included LED firmware to the matching board and identify its serial port.
  • Close other programs using that port. Set LED_SERIAL_PORT to the board port, then run python app.py.
  • Open the local address printed by Flask and use the ON and OFF buttons.

For example, in Windows PowerShell the port can be set with $env:LED_SERIAL_PORT = "COM10". On macOS or Linux, use the actual device path with export LED_SERIAL_PORT=/dev/your-board-port. The port names are examples and must be replaced for the connected board.

Demonstration and reflection

The recording below shows the original interface demonstration. The downloadable package now brings the HTML template, backend and LED firmware together. Its routes and serial command writes have been checked with a simulated serial connection; the packaged revision still needs a repeat physical-board test.

Recorded browser-to-LED demonstration

I learned to test each link separately: the LED firmware, the serial command, the Flask route and the browser action. This makes a failure easier to locate than treating the interface and hardware as one unexplained system.

Application files

Use the ZIP for the complete folder structure. The individual files and setup instructions are also retained.

Handling a missing board and an unconfirmed command

I revised the downloadable package with Codex assistance so it can show the controls even before a board is connected. The first command opens the configured port. A port error produces a useful retry message; if the board does not reply with the expected ON/OFF acknowledgement, the page does not claim that the LED changed.

Actual browser capture of the local LED application with no serial port configured
The revised local interface without a configured board. This screenshot records the application state, not a physical LED test.

The backend serializes commands and rejects foreign browser origins and hostnames. It binds to the local computer and runs without debug mode. The controls are for this lab setup, not a remotely deployed device service. Software checks cover confirmed commands, missing confirmation, a disconnected port and rejected cross-origin requests using a fake serial connection. I still need to repeat the complete package on my fabricated board.