EBC Exercise 32 gpio via flask

From eLinux.org
Jump to: navigation, search

thumb‎ Embedded Linux Class by Mark A. Yoder

This is an introduction to how to control the Beagle via the Web using Flask.

Much of this is from https://towardsdatascience.com/python-webserver-with-flask-and-raspberry-pi-398423cc6f5d.

Installing Flask

Flask should already be installed on the Bone. But if not:

bone$ sudo apt update
bone$ sudo apt install python3-flask

All the examples are in the class repo

bone$ git clone https://github.com/MarkAYoder/BeagleBoard-exercises.git examples
bone$ cd examples/flash/server

First Flask - hello, world

Our first example is helloWorld.py

#!/usr/bin/env python3
# From: https://towardsdatascience.com/python-webserver-with-flask-and-raspberry-pi-398423cc6f5d

from flask import Flask
app = Flask(__name__)
def index():
    return 'hello, world'
if __name__ == '__main__':
    app.run(debug=True, port=8081, host='')

The first line loads the Flask module into your Python script. The second line creates a Flask object called app. The third line is where the action is, it says to run the index() function when someone accesses the root URL (‘/’) of the server. In this case, send the text “hello, world” to the client’s web browser via return.

The last line says to “listen” on port 8081, reporting any errors.

Now on your host computer, browse to an you should see.


Adding a template

Let’s improve our “hello, world” application, creating an HTML template and a CSS file for styling our page.


Create an HTML file that will be located in the “templates” sub-folder, we can use separate files with placeholders for spots where you want dynamic data to be inserted. So, we will create a file named index1.html, that will be saved on /templates.

OK, let’s create templates/index1.html:


(Sorry about using an image here, it kept formatting the HTML tags. Go to the git repo to get the code.)

Note: a style sheet (style.css) is also included. This will be populated later.

Observe that anything in double curly braces within the HTML template is interpreted as a variable that would be passed to it from the Python script via the render_template function. Now, let’s create a new Python script. We will name it app1.py:

# Code created by Matt Richardson 
# for details, visit:  http://mattrichardson.com/Raspberry-Pi-Flask/inde...
from flask import Flask, render_template
import datetime
app = Flask(__name__)
def hello():
   now = datetime.datetime.now()
   timeString = now.strftime("%Y-%m-%d %H:%M")
   templateData = {
      'title' : 'HELLO!',
      'time': timeString
   return render_template('index1.html', **templateData)
if __name__ == "__main__":
   app.run(host='', port=8081, debug=True)

Note that we create a formatted string("timeString") using the date and time from the "now" object, that has the current time stored on it.

Next important thing on the above code, is that we created a dictionary of variables (a set of keys, such as the title that is associated with values, such as HELLO!) to pass into the template. On “return”, we will return the index.html template to the web browser using the variables in the templateData dictionary.

Execute the Python script:

bone$ .\app1.py

Open any web browser and browse to You should see:


Note that the page’s content changes dynamically any time that you refresh it with the actual variable data passed by Python script. In our case, “title” is a fixed value, but “time” change it every second.

Adding Hardware

Wire a button to P9_11 and have the web page display the value of the button.

Let’s create a new Python script and named it app2.py.

#!/usr/bin/env python3
# From: https://towardsdatascience.com/python-webserver-with-flask-and-raspberry-pi-398423cc6f5d
# BeagleBone GPIO Status and Control

import Adafruit_BBIO.GPIO as GPIO
from flask import Flask, render_template
app = Flask(__name__)

button = "P9_11"
buttonSts = GPIO.LOW

# Set button as an input
GPIO.setup(button, GPIO.IN)   

def index():
	# Read Button Status
	buttonSts = GPIO.input(button)
	templateData = {
      'title' : 'GPIO input Status!',
      'button'  : buttonSts,
	return render_template('index2.html', **templateData)
if __name__ == "__main__":
   app.run(host='', port=8081, debug=True)

Look that what we are doing is defining the button on P9_11 as input, reading its value and storing it in buttonSts. Inside the function index(), we will pass that value to our web page through “button” that is part of our variable dictionary: templateData.

Let’s also create a new index2.html to show the GPIO status:


Run it with:

bone$ ./app2.py

Press the button and refresh the page.


Controlling GPIOs

Now that we know how to “read” GPIO Status, let’s change them. What we will do will control via the web page the LED. We have an LED connected to P9_15 . Controlling remotely we will change its status from LOW to HIGH and vice-versa.

The python script Let’s create a new Python script and named it app3.py

#!/usr/bin/env python3
# From: https://towardsdatascience.com/python-webserver-with-flask-and-raspberry-pi-398423cc6f5d
# GPIO Status and Control
import Adafruit_BBIO.GPIO as GPIO
from flask import Flask, render_template, request
app = Flask(__name__)
#define LED GPIOs
ledRed = "P9_15"
#initialize GPIO status variable
ledRedSts = 0
# Define led pins as output
GPIO.setup(ledRed, GPIO.OUT)   
# turn leds OFF 
GPIO.output(ledRed, GPIO.HIGH)

def index():
	# Read Sensors Status
	ledRedSts = GPIO.input(ledRed)
	templateData = {
              'title' : 'GPIO output Status!',
              'ledRed'  : ledRedSts,
	return render_template('index3.html', **templateData)
def action(deviceName, action):
	if deviceName == 'ledRed':
		actuator = ledRed

	if action == "on":
		GPIO.output(actuator, GPIO.HIGH)
	if action == "off":
		GPIO.output(actuator, GPIO.LOW)
	ledRedSts = GPIO.input(ledRed)

	templateData = {
              'ledRed'  : ledRedSts,
	return render_template('index3.html', **templateData)
if __name__ == "__main__":
   app.run(host='', port=8081, debug=True)

What we have new on above code is the new “route”:


From the webpage, calls will be generated with the format:


For the above example, ledRed is the “deviceName” and on or off are examples of possible “action”. Those routes will be identified and properly “worked”. The main steps are:

  • Convert the string “ledRED”, for example, on its equivalent GPIO pin.

The integer variable ledRed is equivalent to P9_15. We store this value on variable “actuator”

  • For each actuator, we will analyze the “action”, or “command” and act properly.

If “action = on” for example, we must use the command: GPIO.output(actuator, GPIO.HIGH)

  • Update the status of each actuator
  • Update the variable library
  • Return the data to index.html

Let’s now create an index.html to show the GPIO status of each actuator and more important, create “buttons” to send the commands:


Run with:

bone$ ./app3.py


The git repo has a forth example, ./app4.py that combines the previous two examples into one app.

thumb‎ Embedded Linux Class by Mark A. Yoder