Subscribe To Our List

We help electronics hobbyists to create projects related to Micro-controllers. Join our newsletter to get access to new projects first.
Email address
Secure and Spam free...

In this Raspberry Pi tutorial, you are going to learn about setting up a Raspberry Pi web server. We will use Flask web framework to create a web server.

Flask is basically a python based web framework which we can use to create a web page where we will show our data and also from where we will control the GPIO pins of Raspberry Pi. Flask can do a lot more than that but in this post, we are just going to create a webpage.

Installing Flask and Creating a Simple Raspberry Pi Web Server

In order to install Flask, you will have to install pip.

sudo apt-get install python-pip

After that, we are going to use pip to install Flask.

sudo pip install flask

Now the flask is installed and its time to run a simple code to test it.

Create a file called “first-flask-project.py” and paste the below code in it.

# Importing the flask module
from flask import Flask

# Create a flask object named app
app = Flask(__name__)

# When someone will enter the IP address of Raspberry Pi in the browser, below code will run.
@app.route("/")
def main():
	return "This is My First Flask Project"

#if code is run from terminal
if __name__ == "__main__":
	# Server will listen to port 80 and will report any errors.
   app.run(host='0.0.0.0', port=80, debug=True)

Now type the following command in the terminal.

sudo python first-flask-project.py

After entering the command in the terminal, you should see the following lines written in the terminal.

Now your web server is created and to access it, you should write the IP address of Raspberry Pi in the browser. If you don’t know the IP address of your Raspberry Pi, then type ‘ifconfig’ and it will tell you the IP address of your Raspberry Pi. You can access the web server from any device connected to the same router as your Raspberry Pi.

If everything is working till now, then its time to move forward and create a proper web page using HTML that will show the data of DHT22 sensor and also will control the GPIO pins of the Raspberry Pi.

Sending DHT22 Data and Controlling GPIO pins from Web Server

To do that, you will have to connect the DHT22 sensor and LED’s with the Raspberry Pi. So, make the circuit as shown below.

After making the circuit, create a folder named “webserver” and in this folder create a file named “my-website.py”. Create another folder in the “webserver” folder and name it as “templates”. In the template folder, create a file named as “main.html”. In the “webserver” folder, create another folder and name it as “static”. Get the files fromĀ http://getbootstrap.com/getting-started/#download and extract them in the static folder. This file will make your webpage a mobile responsive webpage.

Paste the below code in the “my-website.py” file.

from flask import Flask, render_template
import RPi.GPIO as GPIO
import Adafruit_DHT as dht

app = Flask(__name__)

GPIO.setmode(GPIO.BCM)
led1 = 21  
led2 = 20 
DHT22_pin = 16

# Set each pin as an output and make it low:
GPIO.setup(led1, GPIO.OUT)
GPIO.setup(led2, GPIO.OUT)

@app.route("/")

def main():
   return render_template('main.html')

# The function below is executed when someone requests a URL with the pin number and action in it:
@app.route("/<pin>/<action>")
def action(pin, action):
   temperature = ''
   humidity = ''
   if pin == "pin1" and action == "on":
      GPIO.output(led1, GPIO.HIGH)
   
   if pin == "pin1" and action == "off":
      GPIO.output(led1, GPIO.LOW)
   
   if pin == "pin2" and action == "on":
      GPIO.output(led2, GPIO.HIGH)
   
   if pin == "pin2" and action == "off":
      GPIO.output(led2, GPIO.LOW)

   if pin == "dhtpin" and action == "get":
      humi, temp = dht.read_retry(dht.DHT22, DHT22_pin)  # Reading humidity and temperature
      humi = '{0:0.1f}' .format(humi)
      temp = '{0:0.1f}' .format(temp)
      temperature = 'Temperature: ' + temp 
      humidity =  'Humidity: ' + humi

   templateData = {
   'temperature' : temperature,
   'humidity' : humidity
   }

   return render_template('main.html', **templateData)

if __name__ == "__main__":
   app.run(host='0.0.0.0', port=80, debug=True)

Paste the below code in “main.html”

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<head>
   <title>Webserver</title>
   <link rel="stylesheet" media="screen" href ="static/bootstrap.min.css">
   <link rel="stylesheet" href="static/bootstrap-theme.min.css">
   <meta name="viewport" content = "width=device-width, initial-scale=1.0">
 
</head>

<body style="background: grey">
   <h1 align="center"; style="color: navy">Raspberry Pi Webserver</h1>
   <p align="center"><button><a href="/dhtpin/get" style="color: teal"> Get Temperature </a></button></p>
   
   <h4> {{ temperature }} </h4>
   <h4> {{ humidity }} </h4>
   
   <h2 style="color: blue">GPIO21
      <button>
          <a href="/pin1/on" style="color: green"> ON</a>
      </button>
      <button>
         <a href="/pin1/off" style="color: red"> OFF</a>
      </button>
   </h2>

   <h2 style="color: yellow">GPIO20
      <button>
          <a href="/pin2/on" style="color: green"> ON</a>
      </button>
      <button>
         <a href="/pin2/off" style="color: red"> OFF</a>
      </button>
</body>
</html>

Now open the terminal and change directory to your “webserver” folder and type the below command in the terminal.

sudo python my-website.py

After that, type the IP address of your Raspberry Pi in the web browser and it will show you a web page like shown below.

You can also access it from your mobile or tablet.

If you have any questions, feel free to ask in the comment section.

JOIN OUR NEWSLETTER
We help electronics hobbyists to create projects related to Micro-controllers. Join our newsletter to get access to new projects first.
We hate spam. Your email address will not be sold or shared with anyone else.

Leave a Reply

Your email address will not be published.

Subscribe To Our List

We help electronics hobbyists to create projects related to Micro-controllers. Join our newsletter to get access to new projects first.
Email address
Secure and Spam free...
Skip to toolbar