Linux Format

Flask........................................

Les Pounder introduces a Python library to create and interact with physical, real-world electronic­s using a handy web interface.

-

See how Les Pounder uses a Python library to create and interact with physical electronic­s.

Flask is a powerful web server framework for Python and we’re going to use it to control devices connected to a Raspberry Pi via the GPIO Zero library. By turning on an LED using a button on a web page, we introduce how that can be scaled up to do anything with Python and a Raspberry Pi. We also introduce the Bootstrap HTML framework, as used by Twitter, and use it to create a web interface for our controls.

First we’ll connect an LED, inserted into a breadboard. The second part is to connect a motor to the Pi via a controller. We can’t directly connect the motor because it would damage the GPIO pins. See the diagram for clarificat­ion.

To install Flask, open a terminal and type the following to update our repositori­es and then install Flask: $ sudo apt update && sudo apt install python3-flask

We need to find and note the IP address of our Pi: $ hostname -I

The project needs two directorie­s; the first is Flask-Demo $ mkdir Flask-Demo

The second is our templates directory, which contains the HTML of our projects. This is inside the Flask-Demo directory and we can create that using the following command: $ mkdir Flask-Demo/templates

The software for our project is split into two sections. The Python code that will enable us to control the LED and motor and the HTML that is used to create the user interface.

Create the correct code

We’ll start with the Python code. For this open Thonny, found in the Main Menu > Programmin­g. Before we write any code, save your Python project (File > Save) in the Flask-Demo directory. Call the project app.py. Remember to save often.

We start the code by importing three libraries. Flask and its render_template class, GPIO Zero’s LED and Motor classes and from Time we import sleep, which is used to control the pace of our project. from flask import Flask, render_template from gpiozero import LED, Motor from time import sleep

Next, we create two objects to establish a connection between our code, and the LED and motor that’s attached to the Raspberry Pi. The motor object has two parameters: the pins used to control the forwards and backwards movement. led = LED(4) motor = Motor(forward=17, backward=27)

Our next step is to create an app, which is how Flask refers to our project. app = Flask(__name__)

Flask uses “routes”. These are paths that are requested by the user when they either type the path into the address bar, or click a hyperlink that takes them to a certain path.

The first route is our root, identified by /. Here we use render_template to use the index.html file, which we shall later create. We create a function called index that will be called when the user visits the web page. @app.route('/') def index(): return render_template('index.html') We create another route that handles turning the LED on and off using GPIO Zero’s “toggle” function. So when the user visits <IP ADDRESS>/toggle/ the LED will turn on/off as necessary. We also use the same render_template to return the user to the control page. @app.route('/toggle/') def on(): led.toggle() return render_template('index.html') Create two more routes: these will control moving the motor. The code for backwards is the same as forwards, just change ‘forwards’ or ‘backwards’ as applicable. @app.route('/motor-forwards/') def motorforwa­rds(): motor.forward() sleep(1) motor.stop() return render_template('index.html')

Finally, we instruct the Flask app to run. It will write a log to the shell and will accept connection­s from any IP address as we set the host to 0.0.0.0: if __name__ == ‘__main__': app.run(debug=True, host='0.0.0.0')

Save your work and but don’t close We have completed the Python code for this project, so now let’s move to the code for the HTML interface. Thonny. The HTML template is how we provide a user interface for controllin­g the Flask web server. To edit the HTML we’ll need to use Geany, also in the Programmin­g menu. With the Geany window open, click File > Save and navigate to /home/pi/ Flask-Demo/templates. Then save your file as index.html.

We’ll be writing HTML using the Bootstrap framework. We start the HTML by instructin­g the web browser that we’re writing HTML. <!doctype html> <html> <head> <title>Web Controller</title>

Next, we import a Bootstrap CSS stylesheet, used to decorate our page using pre-defined elements such as buttons and grids. We also import two JavaScript libraries to provide interactiv­e elements on the page: <link rel="stylesheet” href="https://maxcdn.bootstrapc­dn. com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/ jquery/3.2.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapc­dn.com/ bootstrap/3.3.7/js/bootstrap.min.js"></script>

We tell the browser to use the full screen space available: <meta name="viewport” content="width=device-width, userscalab­le=no” /> </head>

On to the body! This is the on-screen portion of the HTML. We start by creating a row to store content. This is wrapped in a div : an element to divide up the screen into sections. Our div will create a row with one column where we’ll place an image, in this case the circuit diagram for this project. This will be placed centrally, and it’ll be a quarter of the screen size. <div class="row">

<div class="col-sm-12"><img class="center-block” src="https://raw.githubuser­content.com/lesp/LXF229-Flask/ master/Images/Circuit-Diagram_bb.png” height=25% width=25%> </div> </div> Now let’s create the controls for our project. We’re going to create a container and in there we shall repeat the same div class “row”, but this times we shall create two extra columns that are used to place our controls in the centre of the screen. We start by creating the first column: <div class="container"> <div class="row"> <div class="col-sm-4” style="background-color:white;“></ div> Now we create another column, but in there we place elements such as a title , and some paragraph text

<h2> <p> <div class="col-sm-4” style="background-color:white;“> <h2>Web Controller v 0.3</h2> <p>Click on the buttons to trigger the action</p> We add a new div which will be our group of buttons: <div class="btn-group">

Our group of buttons is made up of three controls, Motor Forward, Toggle LED and Motor Backward. Each button launches a hyperlink – the routes that we set in our Python code. You can see the href for each refers to the routes that we created. Each button also has a class – success, warning and danger – and this colours the buttons accordingl­y.

<a href="/motor-forwards/” data-toggle="tooltip” title="Make the motor spin!” class="btn btn-success">Motor Forward</a>

<a href="/toggle/” data-toggle="tooltip” title="Toggle the LED on or off!” class="btn btn-warning">Toggle LED</a>

<a href="/motor-backwards/” data-toggle="tooltip” title="Send the motor into reverse!” class="btn btndanger">Motor Backward</a> </div>

We now create a final column, the same as the first, then close all of the div elements that we’ve created, before we close the body and the HTML document. Save your work and close the applicatio­n. In Thonny, click the Play button to run the Python code. On another device, connected to the same network, visit the IP address of your Pi, followed by :5000, for example ours was. 192.168.0.6:5000

You will see the interface appear on the screen, so now you can press the buttons and make things come to life! LXF

 ??  ?? Two separate circuits: from the Pi to an LED, and the connection from a DC motor via an L298N controller board.
Two separate circuits: from the Pi to an LED, and the connection from a DC motor via an L298N controller board.
 ??  ??

Newspapers in English

Newspapers from Australia