Read From Gpio Raspberry Pi and Send Data to Server

In this project you'll create a standalone web server with a Raspberry Pi that can toggle two LEDs. You can supplant those LEDs with whatsoever output (like a relay or a transistor).

In lodge to create the web server you volition be using a Python microframework chosen Flask.

Parts Required

Here'southward the hardware that you demand to consummate this project:

  • Raspberry Pi (any Pi should piece of work, I recommend using Raspberry Pi 3) – read All-time Raspberry Pi Starter Kits
  • SD Card (minimum size 8Gb and class 10)
  • Micro USB Power Supply
  • Ethernet cable or WiFi dongle
  • Breadboard
  • 2x LEDs
  • 2x 470Ω Resistors
  • Jumper wires

Raspberry Pi 3

Yous can utilise the preceding links or go directly to MakerAdvisor.com/tools to notice all the parts for your projects at the all-time price!

Basic Raspberry Pi Setup

Before you go on reading this project, please make sure yous have Raspbian Operating System installed in your Raspberry Pi.

You lot tin can read my Getting Started with the Raspberry Pi Guide to install Raspbian and consummate the basic setup.

Installing Flask

We're going to use a Python microframework called Flask to plough the Raspberry Pi into spider web server.

To install Flask, you'll need to accept pip installed. Run the following commands to update your Pi and install pip:

[email protected] ~ $ sudo apt-get update [email protected] ~ $ sudo apt-become upgrade [email protected] ~ $ sudo apt-become install python-pip python-flask

Then, you use pip to install Flask and its dependencies:

          [electronic mail protected] ~ $ sudo pip install flask        

Schematics

The schematics for this project are adequately straightforward. Simply connect 2 LEDs to pins GPIO 23 and GPIO 24, equally the figure below illustrates.

RPi Web Server outputs_bb

Creating the Python Script

This is the core script of our application. It sets up the web server and really interacts with the Raspberry Pi GPIOs.

To keep everything organized, commencement by creating a new folder:

          [electronic mail protected] ~ $ mkdir spider web-server [email protected] ~ $ cd spider web-server [email protected]:~/web-server $                  

Create a new file chosen app.py.

          [email protected]:~/web-server $ nano app.py        

Copy and paste the following script to your Raspberry Pi (this code is based on Matt Richardson not bad example).

          '''  Adapted excerpt from Getting Started with Raspberry Pi past Matt Richardson  Modified past Rui Santos Complete project details: https://randomnerdtutorials.com  '''  import RPi.GPIO as GPIO from flask import Flask, render_template, request app = Flask(__name__)  GPIO.setmode(GPIO.BCM)  # Create a dictionary called pins to store the pin number, proper noun, and pin state: pins = {    23 : {'proper noun' : 'GPIO 23', 'state' : GPIO.LOW},    24 : {'proper noun' : 'GPIO 24', 'state' : GPIO.Depression}    }  # Prepare each pin equally an output and make it low: for pin in pins:    GPIO.setup(pivot, GPIO.OUT)    GPIO.output(pin, GPIO.LOW)  @app.route("/") def principal():    # For each pivot, read the pin state and store it in the pins dictionary:    for pin in pins:       pins[pivot]['state'] = GPIO.input(pin)    # Put the pivot dictionary into the template data lexicon:    templateData = {       'pins' : pins       }    # Pass the template information into the template main.html and return it to the user    return render_template('main.html', **templateData)  # The function below is executed when someone requests a URL with the pivot number and action in information technology: @app.route("/<changePin>/<action>") def activeness(changePin, action):    # Convert the pin from the URL into an integer:    changePin = int(changePin)    # Get the device name for the pin being changed:    deviceName = pins[changePin]['name']    # If the action part of the URL is "on," execute the code indented beneath:    if action == "on":       # Set the pin high:       GPIO.output(changePin, GPIO.Loftier)       # Salve the status bulletin to exist passed into the template:       message = "Turned " + deviceName + " on."    if action == "off":       GPIO.output(changePin, GPIO.LOW)       message = "Turned " + deviceName + " off."     # For each pivot, read the pivot country and store information technology in the pins dictionary:    for pin in pins:       pins[pin]['state'] = GPIO.input(pin)     # Forth with the pin lexicon, put the message into the template data dictionary:    templateData = {       'pins' : pins    }     return render_template('main.html', **templateData)  if __name__ == "__main__":    app.run(host='0.0.0.0', port=80, debug=True)                  

View raw lawmaking

Creating the HTML File

Keeping HTML tags separated from your Python script is how you keep your project organized.

Flask uses a template engine called Jinja2 that you tin can use to send dynamic information from your Python script to your HTML file.

Create a new binder called templates:

[email protected]:~/web-server $ mkdir templates [electronic mail protected]:~/web-server $ cd templates [email protected]:~/web-server/templates $

Create a new file called main.html.

[email protected]:~/spider web-server/templates $ nano main.html

Copy and paste the following template to your Pi:

          <!DOCTYPE html> <head>    <title>RPi Web Server</title>    <!-- Latest compiled and minified CSS -->    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">    <!-- Optional theme -->    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/iii.3.6/css/bootstrap-theme.min.css" integrity="sha384-fLW2N01lMqjakBkx3l/M9EahuwpSfeNvV63J5ezn3uZzapT0u7EYsXMjQV+0En5r" crossorigin="anonymous">    <!-- Latest compiled and minified JavaScript -->    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.iii.vi/js/bootstrap.min.js" integrity="sha384-0mSbJDEHialfmuBBQP6A4Qrprq5OVfW37PRR3j5ELqxss1yVqOtnepnHVP9aJ7xS" crossorigin="anonymous"></script> </head>  <body>    <h1>RPi Spider web Server</h1>    {% for pivot in pins %}    <h2>{{ pins[pin].proper name }}    {% if pins[pin].land == true %}       is currently <stiff>on</strong></h2><div class="row"><div grade="col-doctor-ii">       <a href="/{{pivot}}/off" class="btn btn-cake btn-lg btn-default" role="button">Plow off</a></div></div>    {% else %}       is currently <stiff>off</strong></h2><div class="row"><div class="col-medico-ii">       <a href="/{{pin}}/on" form="btn btn-block btn-lg btn-primary" role="button">Turn on</a></div></div>    {% endif %}    {% endfor %} </body> </html>                  

View raw code

Launching the Web Server

To launch your Raspberry Pi web server motility to the folder that contains the file app.py:

[electronic mail protected]:~/web-server/templates $ cd ..

Then run the following command:

[email protected]:~/web-server $ sudo python app.py

Your web server should showtime immediately!

python launch web server

Demonstration

Open up your Raspberry Pi address in your browser by entering its IP address, in my example:http://192.168.1.98/.

rpi web server browser

Here's a video demo of the web server in action.

I promise you've found this tutorial useful.

Share this post with a friend that also likes electronics!

Y'all can contact me by leaving a comment. If y'all like this postal service probably y'all might like my next ones, so please back up me by subscribing my blog.

Cheers for reading,

-Rui Santos

pullenwhippyraton1972.blogspot.com

Source: https://randomnerdtutorials.com/raspberry-pi-web-server-using-flask-to-control-gpios/

0 Response to "Read From Gpio Raspberry Pi and Send Data to Server"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel