WARP

Weather According to Raspberry Pi


Using the SenseHAT, a bit of Python and some HTML, you can see the weather conditions on your phone or laptop

If the Pi is outside monitoring the temperature, humidity and pressure, then it makes sense that you want to be able to see the data without having to go outside to look.


Advertisement



This project lets you see what you Pi sees but conveniently, as a web page.

There are only two files needed but they represent quite a lot of typing, so I'll provide a link, below, where you can download them. 

I'll be using the desktop SenseHAT emulator to demonstrate this so you don't actually need a SenseHAT to see it working. When you want to change to the real hardware, you simply need to change one line of code.

If you are using the latest version of Raspbian then you will already have the SenseHAT emulator (note this is not the web based emulator, it's the desktop one).

What you may not have is Flask. Flask is a lightweight framework for creating web applications in Python. That may sound complicated but it really isn't. So open a Terminal Window and type
pip3 install flask

and when it's finished we are ready.

For this first article I'm just going to show you how to install the files and run them. I'll explain their operation later when you have had a chance to play.

So get the files here.
http://coded2.herokuapp.com/weather/
Or, if you don't want to download from an unknown source (and who can blame you!), I have appended the files to the end of this blog and you can cut and paste from there.

Just click on the link and your browser should download the zip file. Next open the file manager and find the downloaded file. You need to open the zip file with the Archiver, double clicking should do it.

When it's opened you should see that it contains a single folder called final and you need to extract this somewhere sensible. I have a folder for Python projects inside the documents folder - that, for example, would be a suitable place.

Now open a Terminal window and navigate to the folder final. If you type ls you will see the file main.py and a folder called templates (this contains a single file called gauge2.html).

Now we need to start the SenseHAT emulator. You'll find it under the programming menu. When started it will look something like this


Next, back to the terminal window. From within the folder final type
python3 main.py
In the terminal window, you should see a message that tells you that there is a server running on port 5000. This means that you can open your browser and type
localhost:5000
in the address bar and you will get the screen shown at the top of this article. And if you play with the sliders in the SenseHAT emulator, the needles on the gauges will respond accordingly.

The screen refreshes every 5 seconds, if you can't wait that long you can press the update button.

That's not bad, but it gets better!

If you know the ip address of your Pi you can ignore this next bit. If not open a Terminal window and type
/sbin/ifconfig
then, in the response, look for inet addr, there may be two, you do NOT want the one that is 127.0.0.1. Mine is 192.168.1.170, yours will be different but similar.

Now for the good bit!

Get your phone or laptop and open a browser. In the address bar type

192.168.1.17:5000

Actually, not that, of course. You need to type your own ip address followed by a colon and then 5000.

You should see the same screen on your phone/laptop. Again play around with the sliders on the emulator and the dials will respond.

That's all very well but you probably want to use a real SenseHAT. Easy. Open the file main.py in an editor and find the import statement. Where it says
from sense_emu import SenseHat
 change it to
from sense_hat import SenseHat
and save it.

Now you need to restart the program. In the terminal window where you ran the Python program, type control-c, to stop it running. Then start it again (python3 main.py).

Now you should see the real temperature, pressure and humidity as read from the real SenseHAT.

OK, that's it for now. Explore the code for yourself and I'll write an explanation later.



Advertisement



Files to cut and paste

Here are the files to cut and paste, if you don't want to download them. The first is the Python file, main.py, the next is an html file, gauge2.html

You need to create a folder for them, to be consistent with the instructions above, call it final (although its name is actually not important) and then create main.py there. Now create a folder templates inside final and put gauge2.html in there.

main.py

import flask
from sense_emu import SenseHat
import json
sense = SenseHat()
app = flask.Flask(__name__)
@app.route("/")
def hello():
return  flask.render_template("gauge2.html", temp=round(sense.temp,1), hum=round(sense.humidity,0), press=round(sense.pressure,0))
@app.route("/getTemp/")
def getTemp():
result = json.dumps([round(sense.temp,1),round(sense.humidity,0),round(sense.pressure,0)])
return result
if __name__ == "__main__":
app.run(host='0.0.0.0')

gauge2.html

<html>
 <head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.gaugeDiv{
display: inline-block;
width:30%;
}
</style>
  <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
  <script type="text/javascript">
    google.charts.load('current', {'packages':['gauge']});
    google.charts.setOnLoadCallback(drawAll);
    var gaugeOptions = {min: 0, max: 100, minorTicks: 5};
    var gauge;
    var gaugeData;
    var pressureGaugeOptions = {min: 200, max: 1500, minorTicks: 10};
    var pressureGauge;
    var pressureGaugeData;
    var humidityGaugeOptions = {min: 0, max: 100, minorTicks: 5};
    var humidityGauge;
    var humidityGaugeData;
 
    function drawAll(){
drawGauge();
drawPressureGauge();
drawHumidityGauge();
}
    function drawGauge() {
 gaugeData = new google.visualization.DataTable();
      gaugeData.addColumn('number', 'Temp.');
      gaugeData.addRows(1);
      gaugeData.setCell(0, 0, {{temp}});
      gauge = new google.visualization.Gauge(document.getElementById('gauge_div'));
      gauge.draw(gaugeData, gaugeOptions);  
    }
    function drawPressureGauge() {
 pressureGaugeData = new google.visualization.DataTable();
      pressureGaugeData.addColumn('number', 'Pressure');
      pressureGaugeData.addRows(1);
      pressureGaugeData.setCell(0, 0, {{press}});
   
      pressureGauge = new google.visualization.Gauge(document.getElementById('pGauge_div'));
      pressureGauge.draw(pressureGaugeData, pressureGaugeOptions);  
    }
    function drawHumidityGauge() {
 humidityGaugeData = new google.visualization.DataTable();
      humidityGaugeData.addColumn('number', 'Humidity');
      humidityGaugeData.addRows(1);
      humidityGaugeData.setCell(0, 0, {{hum}});
   
      humidityGauge = new google.visualization.Gauge(document.getElementById('hGauge_div'));
      humidityGauge.draw(humidityGaugeData, humidityGaugeOptions);  
    }
 
    function updateGauge(){
gauge.draw(gaugeData, gaugeOptions);
pressureGauge.draw(pressureGaugeData, pressureGaugeOptions);
humidityGauge.draw(humidityGaugeData, humidityGaugeOptions);
}
function makeRequest(){
         request = new XMLHttpRequest();
         request.onreadystatechange = function(){
            if (request.readyState === XMLHttpRequest.DONE) {
                if (request.status === 200) {
                   result = (JSON.parse(request.responseText));
                   //alert(result[1]);
                   gaugeData.setCell(0, 0, result[0]);
                   humidityGaugeData.setCell(0, 0, result[1]);
                   pressureGaugeData.setCell(0, 0, result[2]);
                   updateGauge();
                } else {
                   alert('There was a problem.');
                }
            }
         };
         request.open('GET',"/getTemp", true);
         request.send();
      }
function makeAllRequests(){
makeRequest();
}  setInterval(makeAllRequests, 5000);
  </script>
 </head>
 <body>
  <div style="background-color:silver;margin:10px;padding:10px;border-style:solid;border-width:2px">
 <h3 style="font-family:arial, sans-serif; text-align:center">Weather According to Raspberry Pi</h3>
  <div id="gauge_div" class="gaugeDiv"></div>
  <div id="pGauge_div" class="gaugeDiv"></div>
  <div id="hGauge_div" class="gaugeDiv"></div>
  <button onclick="makeRequest()">Update</button>
 </div>
 </body>
</html>

Comments

  1. so is there any more hardware to buy? I am confused, how does Sensehat work? a RPI can sense temperature without added hardware, just download Sensehat?

    ReplyDelete
    Replies
    1. I am not aware that the Pi can sense the temperature without a SenseHAT. This is written for the SenseHAT hardware, or the desktop SenseHAT emulator (that is included in Raspian). You need to obtain the hardware or use the emulator. You can find out about the hardware from the Raspberry Pi web site
      https://www.raspberrypi.org/products/sense-hat/

      Delete

Post a Comment

Popular posts from this blog

Just Enough Python

Learn to code with C

Introduction to Python by Andrew Ng