Communicating With Raspberry Pi Using HTTP

Communicating With Raspberry Pi Using HTTP

The Raspberry PI is a board with which we can experiment and create all kinds of projects, such as turning on an LED. Wouldn’t it be nice if we could remotely control the GPIO ports and maybe play a tune or turn a LED on and off using a web interface? Let’s find out! Let’s see how to communicate with the Raspberry PI using HTTP.

Required Components

For this project, you need the following components:

  • 1 Breadboard
  • 1 Raspberry Pi 3 B
  • 1 Piezo
  • 1 LED
  • 1 resistor (220Ω)
  • 4 wires

Circuit

Now, let’s proceed with creating the circuit.

  • Connect the Piezo to the breadboard.
  • Connect a wire from GPIO port 17 to the positive of the Piezo.
  • Connect a wire from GND to the negative of the Piezo.
  • Connect the LED to the breadboard.
  • Put the resistor in series on the longest pin of the LED.
  • Connect a wire from GPIO port 13 to the resistor.
  • Finally connect a wire from GND to the free pin of the LED.
Communicating With Raspberry Pi Using HTTP

Code

Now let’s write the code to communicate with our Raspberry Pi. In this project we’ll use Python as programming language, and the GPIOzero and Flask libraries.

  • Create a file named app.py
  • Paste the following code.
from flask import Flask, render_template
from gpiozero import LED, TonalBuzzer

app = Flask(__name__)
led = LED(13)
buzz = TonalBuzzer(17)


@app.route('/')
def index():
    return render_template('index.html')


@app.before_request
def before():
    led.on()


@app.after_request
def after(response):
    led.off()
    return response


@app.route('/piezo/status', methods=['POST'])
def toggle():
    if buzz.is_active:
        buzz.stop()
    else:
        buzz.play(220)
    return {"status": buzz.is_active}


if __name__ == "__main__":
    app.run()

In the first lines we initialize Flask, the LED and the TonalBuzzer. The index function is used to return our home page, while before and after functions are called when a request is received and an HTTP response is sent. In these functions, as you can see, we turn the LED on and off. The toggle function is used to alternate the state of the piezo and therefore make it play or stop depending on the state it is in.

HTML Template

At this point it’s time to create our welcome page.

  • Create a directory named templates ( By default Flask looks in this folder)
  • Create a file named index.html
  • Paste the following code.
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Raspberry Pi HTTP</title>
    <link rel="stylesheet" type="text/css" href="{{ url_for('static',filename='css/index.css') }}">
  </head>
  <body>
    <h1>Welcome</h1>
    <button id="toggle-btn" class="btn">Toggle Sound</button>
    <script src="{{ url_for('static', filename='js/index.js') }}"></script>
  </body>
</html>

As you can see on this page we have a simple title and a button that will later allow us to alter the state of the piezo. We also defined a link to load a css file and a script to load a js file. The url_for() function serves to generate the appropriate file location. The first argument specifies that you are linking to a static file and the second argument is the path to the file within the static directory.

Now let’s proceed by creating a folder called static at the same level as the templates folder. Once this is done we can move on to creating our css file.

  • Create a directory named css
  • Create a file named index.css
  • Paste the following code.
.btn {
  color: #fff;
  background-color: #307fff;
  padding: 8px 24px;
  border-width: 0;
  border-radius: 24px;
  cursor: pointer;
}
.btn:hover {
  background: #307fffcc;
}

Now let’s proceed with creating our JS file.

  • Create a directory named js inside the static directory.
  • Create a file named index.js
  • Paste the following code.
document.getElementById("toggle-btn").addEventListener("click", () => {
	var http = new XMLHttpRequest();
	var url = 'piezo/status';
	http.open('POST', url, true);
	http.onreadystatechange = function() {
		if (http.readyState == 4 && http.status == 200) {
			console.log(http.responseText);
		}
	}
	http.send();
});

In this file we simply listen to the click of our button, executing an HTTP call to our piezo/status endpoint which will change the state of the piezo.

Application Testing

Now that everything is ready we can test our application.

  • Open the terminal and navigate to your project folder.
  • Run python app.py
  • Open the browser and type the following URL: http://localhost:5000 (Flask default port)

If everything went correctly you should see the same screen as the image above. Now if you try to press the button the piezo should start beeping and if you click again it should stop, while the LED will blink with every HTTP request received.

Conclusion

This was a simple project that introduced the essential concepts of the Flask framework and that allowed us to understand how it is possible to communicate with the Raspberry Pi using HTTP. You can further develop this application by adding new components or simply changing the tune of the piezo.
Source code is available on GitHub.

Lorenzo Miscoli

Software Developer specialized in creating and designing web applications. I have always loved technology and dreamed of working in the IT world, to make full use of my creativity and realize my ideas.
Scroll to Top