16
Connecting your Electronics to the Web

In this project you’ll create your own Internet of Things web server you can use to control a lamp remotely from your phone. The simple web server you’ll build can then be added to other projects so you can control other electronic appliances.

image

PARTS REQUIRED

Raspberry Pi

Relay module HL-52S

12 V lamp and holder

12 V power adapter

Male DC bar rel power jack

Plastic box enclosure

Jumper wires

SOFTWARE REQUIRED

Flask framework

In this project you’re going to create your own web server to control your electronics through a browser. You’ll control a 12 V lamp using a dynamic web page with buttons.

INTRODUCING WEB SERVERS

A web server is a computer that provides web pages. It stores the website’s files, including all HTML documents and related assets like images, CSS style sheets, fonts, and video. It also brings those files to the user’s device web browser when the user makes a request to the server’s URL.

When you access a web page in your browser, you’re actually sending a request via Hypertext Transfer Protocol (HTTP) to a server. This is simply a process for requesting and returning information on the internet. The server sends back the web page you requested—also through HTTP.

In this project you’ll use your Raspberry Pi to host a web server on the local network, as illustrated in Figure 16-1.

image

FIGURE 16-1: Your Raspberry Pi running a web server

As a server, your Raspberry Pi can provide some output through its GPIO pins. In other words, using a browser on your local network, you can access the Pi web server to remotely control the GPIOs and turn something on.

Web servers can serve static or dynamic content. The content of a static website doesn’t change unless you edit its HTML file. The website built in Project 15 is an example of a static website. With a dynamic website, the content changes based on user interactions. In this project, you’ll create a dynamic website that controls and shows the current state of a 12 V lamp connected to a relay, which we’ll look at more closely in a second.

NOTE

Only devices that are connected to the same router as your Pi can access a web page hosted in your Pi through a browser. Accessing your web server from outside your network is more difficult. You can make your Raspberry Pi web server accessible from any computer anywhere by using a technique called router port forwarding, but that subject is beyond the book’s scope.

INTRODUCING THE RELAY MODULE

A relay is an electrically operated switch that can be turned on or off, letting the current go through or not, and can be controlled with low voltages, like the 3.3 V provided by the Raspberry Pi. The relay module you’ll use in this project has two relays—the two blue cubes shown in Figure 16-2.

image

FIGURE 16-2: Relay module with two channels

The six pins on the left side of the relay module connect high voltage, and the pins on the right side connect the component that requires low voltage—the Raspberry Pi GPIOs.

Relay Pinout

The high-voltage side has two connectors, each with three sockets: common (COM), normally closed (NC), and normally open (NO). The normally closed configuration is used when you want the relay to be closed by default, meaning the current is flowing unless you send a signal from the Pi to the relay module to open the circuit and stop the current. The normally open configuration works the other way around: the relay is always open, so the circuit is broken unless you send a signal from the Pi to close it.

The low-voltage side has a set of four pins and a set of three pins. The first set consists of VCC and GND to power up the module, and input 1 (IN1) and input 2 (IN2) to control the bottom and top relays, respectively. The second set of pins consists of GND, VCC, and JD-VCC pins. The JD-VCC pin powers the electromagnet of the relay. Notice that the module has a jumper cap connecting the VCC and JD-VCC pins; the one shown here is blue, but yours may be a different color.

The jumper cap allows you to choose whether the circuit is physically connected to the Pi circuit or not, and you can choose to have it on or not. With the jumper cap on, the VCC and JD-VCC pins are connected. That means the relay electromagnet is directly powered from the Pi’s power pin, so the relay module and the Raspberry Pi circuits are not physically isolated from each other. This is the configuration we’ll use. Without the jumper cap, you need to provide an independent power source to power up the relay’s electromagnet through the JD-VCC pin. That configuration physically isolates the relays from the Raspberry Pi with the module’s built-in optocoupler, which prevents damage to the Pi in case of electrical spikes.

THE OPTOCOUPLER

We won’t go into too much detail about the optocoupler. It is basically a component that allows you to send signals between two isolated circuits so that you can control high voltages with low voltages without actually having a physical connection between those two circuits. The optocoupler makes the “connection” between the circuits using an LED that emits light and a phototransistor that receives the light and then activates or deactivates the relay.

Relay Usage

You’ll use a normally open configuration for this project. You want to light the lamp only when you choose to, so the circuit should be broken until you say otherwise. For this, you use the COM and NO sockets.

In a normally open configuration, there is no contact between the COM and NO sockets unless you trigger the relay. The relay is triggered when the input goes below about 2 V. That means if you send a LOW signal from the Pi, the relay turns on, and if you send a HIGH signal, the relay turns off; this is called inverted logic. You’ll control just one relay, so you’ll connect IN1 to one of the Pi’s GPIO pins.

WARNING

If you’re not comfortable dealing with higher voltages like 12 V, but you want to do the project, you can replace the relay module with an LED. You’ll also need to make some minor changes to the Python script, since the relay works with inverted logic and the LED doesn’t.

The hardware for the project involves connecting an AC 12 V power adapter that can provide 1 A to a relay module to control a 12 V lamp. We’ll use a DC barrel power jack to make the connections between the adapter and the relay easier. The barrel jack connects perfectly to the power adapter terminal, as shown in Figure 16-3.

image

FIGURE 16-3: Power adapter terminal and DC barrel power jack

PROJECT OVERVIEW

Before getting into building this project, let’s go through a quick overview so you better understand each step (see Figure 16-4). You should also know the basics of HTML and CSS, so we recommend that you complete Project 15 if you haven’t already before moving on.

image

FIGURE 16-4: Project overview

You’ll create your web server with Flask, a Python web framework, by creating a file called app.py. When you access the Raspberry Pi IP address, port 80, your web browser requests the web page files stored in your Raspberry Pi—index.html and style.css—and then displays the web page. Your web page will have ON and OFF buttons that trigger an event that turns the lamp on and off, respectively.

WIRING THE CIRCUIT

For safety reasons, you’ll want to place your relay inside a plastic box enclosure. You may need to drill some holes in the plastic box for the wires—one hole for the Pi wires, another for the lamp wires, and one for the power adapter. Figure 16-5 shows how the enclosure looks without the lid. The Raspberry Pi wires will go through a hole on the lid.

image

FIGURE 16-5: Circuit with the relay in a plastic box enclosure

NOTE

Make sure you have the jumper cap on the JD-VCC and VCC pins.

With your Pi powered off, follow these instructions to build the circuit:

  1. Connect one of the lamp holder terminals to the negative (–) terminal on the DC barrel power jack.

  2. Connect the DC barrel power jack positive (+) terminal to the relay COM socket.

  3. Connect the other lamp terminal to the relay NO socket. You need a screwdriver to connect the relay sockets tightly.

  4. Follow the table to wire the Raspberry Pi to the relay, and make sure your completed setup matches Figure 16-6.

    RELAY

    RASPBERRY PI

    VCC

    5 V

    IN2

    Don’t connect

    IN1

    GPIO 17

    GND

    GND

    image

    FIGURE 16-6: Controlling a 12 V lamp with the Raspberry Pi using a relay

WARNING

Do not touch the relay or any live wires while they are connected to 12 V. If something isn’t working and you decide to make changes to the circuit, remove the 12 V power adapter plug from the socket before touching anything.

After completing the circuit and double-checking all the connections, apply power to the Raspberry Pi, connect a 12 V power adapter to the DC barrel power jack, and apply power by plugging the 12 V power adapter into a wall socket.

If you want to control an LED instead, use the Project 1 schematic diagram on page 41 as a reference, connecting the LED to GPIO 17.

PREPARING YOUR PI TO RUN A WEB SERVER

The Raspberry Pi supports a number of web servers, but we’re going to use Flask, a Python web framework, to turn the Pi into a dynamic web server.

Installing Flask

To install Flask, you need to have pip, a tool to install libraries from the Python Package Index. Open the terminal and run the following commands to update your Pi and install pip:

pi@raspberrypi:~ $ sudo apt update && sudo apt upgrade
pi@raspberrypi:~ $ sudo apt install python3-pip

Then use pip to install Flask and its dependencies by entering the following:

pi@raspberrypi:~ $ sudo pip3 install flask

If Flask installs correctly, the terminal will display the message successfully installed Flask.

Organizing Your Files

Keeping your files organized is essential in this project because Flask needs your files structured in a particular way to work correctly. Create a folder specifically for this project called Project_16 inside the Web_Applications folder. Then create the folders and files you’ll need by following the structure shown in Figure 16-7.

image

FIGURE 16-7: Files and folders structure

Create the index.html and style.css files using the Text Editor and the app.py file using Python 3 (IDLE). The static folder will store static files like the CSS file. The templates folder will store files that can be changed; for example, the index.html file is a template that dynamically changes the relay status label according to user input.

WRITING THE SCRIPTS

You’ll need to write three scripts for this project: a Python script that will create your Pi web server, an HTML file that builds your web page, and a CSS file to style your web page.

Creating the Web Server

To create the web server, open your app.py file, currently empty, and enter the code in Listing 16-1. This code creates the web server on Raspberry Pi port 80 and generates a web page that you can access on the local network, from any web browser. You can download all the code used throughout this project at https://www.nostarch.com/RaspberryPiProject/.

LISTING 16-1: Creating a web server with Flask

  #import necessary libraries
from gpiozero import LED
  from flask import Flask, render_template, request

  #create a Flask object
app = Flask(__name__)

  #create an object that refers to a relay
relay = LED(17)
  #set the relay off; remember the relay works with inverted logic
  relay.on()
  #save current relay state
  relay_state = 'Relay is off'

  #display the main web page
@app.route('/')
  def main():
     global relay_state
     #pass the relay state to index.html and return it to the user
    return render_template('index.html', relay_state=relay_state)

  #execute control() when someone presses the on/off buttons
@app.route('/<action>')
  def control(action):
     global relay_state
     #if the action part of the URL is 'on', turn the relay on
    if action == 'on':
        #set the relay on
        relay.off()
        #save the relay state
        relay_state = 'Relay is on'
     if action == 'off':
        relay.on()
        relay_state = 'Relay is off'

     #pass the relay state to index.html and return it to the user
     return render_template('index.html', relay_state=relay_state)
  #start the web server at localhost on port 80
  if __name__ == '__main__':
   app.run(host='0.0.0.0', port=80, debug=True)

First you import the needed libraries , and then you create a Flask object called app . You initialize the relay on GPIO 17 and set the relay as off by default. The relay works with inverted logic, so you use relay.on() to turn it off.

The @app.route('/') decorator runs the main() function when someone accesses the root URL—the main Pi IP address of the server. In Python, a decorator starts with the @ symbol and goes above a function definition. A decorator is basically a function that takes in another function, but you don’t need to worry about this for the moment.

You render the index.html file to the web browser and print the current relay state, using the relay_state variable value on the HTML file . Then you add a dynamic route with action as a variable . This runs the control() function when someone accesses the dynamic route. If the action from the URL is on, the program turns the relay on and saves the current relay state . This means when you access your Raspberry Pi IP address followed by /on (for example, http://192.168.1.112/on), the relay turns on. You’ll fetch your own IP address shortly.

If the action from the URL is off, the program turns the relay off and saves the current relay state. The server is listening on port 80 and the debug is set to True to report any errors .

Writing the HTML File

Listing 16-2 is a simple HTML document that structures the web page. Feel free to add more paragraphs and headings to personalize it using what you learned in Project 15. Copy this code to your index.html file, which should be located in the templates folder as shown earlier in Figure 16-7.

LISTING 16-2: Writing the HTML file for your web page

  <!DOCTYPE html>
  <head>
  <title>RPi Web Server</title>
  <link rel="stylesheet" type="text/css" href="{{ url_for('static',
  filename='style.css') }}">
<meta name="viewport" content="width=device-width, initial-scale=1">
  </head>

  <body>
      <h2>RPi Web Server</h2>
    <p>{{relay_state}}</p>
    <a href="/on"><button>ON</button></a>
    <a href="/off"><button class="off">OFF</button></a>
  </body>
  </html>

This is a simple HTML structure, and we won’t go into too much detail in this HTML code, because you should already be familiar with most of it from Project 15. You can always refer back to that project for a refresher.

The <meta> tag and the given attributes make your web page responsive in any mobile browser . With this tag, the browser will render the width of the page to the width of the mobile screen. At line , between double curly brackets {{ }}, is relay_state, the variable we’re using in app.py to save the current relay state. This paragraph displays the state saved in the relay_state variable. When you click the ON button, you are redirected to /on root , which turns the relay on, as seen in app.py. When you click the OFF button, you are redirected to the /off root , which turns the relay off.

Writing the CSS File

Listing 16-3 styles your web page. This is just an example of how you can style your page; you can edit the properties as you like. Your style.css file should be inside the static folder, as you saw earlier in Figure 16-7.

LISTING 16-3: Styling the web page with CSS

h2 {
    font-size: 2.5rem;
  }
  p {
    font-size: 1.8rem;
  }
body {
    display: inline-block;
    margin: 0px auto;
    text-align: center;
  }
button {
    display: inline-block;
    margin: 0 auto;
    padding: 15px 25px;
    font-size: 3rem;
    border-radius: 4px;
    color: #fff;
    background-color: #009933;
    border: none;
  }
  .off {
    color: #fff;
    background-color: #604f43;
  }
  a {
    text-decoration: none;
  }

In summary, we’ve set font sizes for the heading 2 and the paragraph . Then, we’ve aligned all our page body . Finally, we’ve edited the appearance of the ON and OFF buttons .

Launching Your Web Server

With the Python script, HTML file, and CSS file completed, it’s time to run your web server. Open the terminal window and navigate to the Project_16 folder by entering this command:

pi@raspberrypi:~ $ cd ~/Desktop/Projects/Web_Applications/Project_16

Then, run app.py with the following line:

pi@raspberrypi:~Desktop/Projects/Web_Applications/Project_16 $ sudo
python3 app.py

Your web server is now running. Open any browser on the local network and enter your Raspberry Pi IP address.

To find your Pi’s IP address, go to the terminal and enter the following:

pi@raspberrypi:~ $ hostname -I

This prints the Pi’s IP address.

With your circuit ready and your server running, open a browser and navigate to your Raspberry Pi IP address. Your browser will display the web server page. Now click the buttons to remotely control the lamp! Figure 16-8 shows the web page in a smartphone’s browser.

image

FIGURE 16-8: Raspberry Pi web server page on a smartphone’s browser

To stop the web server, simply press CTRL-C.

TAKING IT FURTHER

In this project, you learned how to use a relay and how to set up a web server to serve a web page, as well as put your HTML and CSS skills into practice. Here are some ideas for taking these concepts further:

  • Edit this project to control more than one output.
  • Edit the CSS and HTML files to suit your own tastes.
  • Control other electronic appliances.
  • Edit previous projects to control lamps connected to relays instead of LEDs.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.83.151