staffyman
Posts: 7
Joined: Thu Sep 20, 2018 11:04 am
Location: Doncaster, South Yorkshire

Pi ZeroW room thermometer [solved]

Thu Sep 20, 2018 11:21 am

Hello everybody,
I'm totally new to the world of Raspberry Pi and my son has asked me to buy one so we can tinker.
We've come up with a project to have a digital thermometer in the room showing temperature and humidity on a small screen.
I've purchased a Pi ZeroW, a small 128x64 OLED SSD1306 screen and an AM2302(DHT22).
Using the guides on Adafruit website, I managed to get the display working and the temperature readings from the AM2302.
These are the pages visited to get them working:
Screen: https://learn.adafruit.com/ssd1306-oled ... k?view=all
AM2302: https://learn.adafruit.com/dht-humidity ... ll-updated

My question is, how do I get the Pi to take regular readings of, say every 5 minutes, and show it on the little screen? I also want it to run automatically at boot up.

I know nothing of how to code or use programming languages, so this really will have to be a 'handheld' approach from you people.

Summary of hardware/software used:
Raspberry Pi Zero W
Latest Raspbian Lite from raspberrypi.org
AM2302 module from Ebay
0.96" ssd1306 OLED screen from Ebay
and got them tested using the aforementioned Adafruit guides over ssh.

Looking forward to your help and seeing the results.

scotty101
Posts: 3100
Joined: Fri Jun 08, 2012 6:03 pm

Re: Pi ZeroW room thermometer

Thu Sep 20, 2018 1:49 pm

staffyman wrote:
Thu Sep 20, 2018 11:21 am
I know nothing of how to code or use programming languages, so this really will have to be a 'handheld' approach from you people.
This is your project.
Most people on this forum are happy to point people in the right direction, recommend similar tutorials or help people debug their code but 'handholding' though such a project just isn't practical given that you are starting as a total beginner.

Would you start learning how to fly a plane by being put in to a 747 and having someone tell you what to do? No?
Same with programming. You start by learning the basics of programming in a specific language, and build your skills until you are able to progress to more complex programs and are finally able to take on completing your own project.

Start in places like the projects and tutorials on this website
https://projects.raspberrypi.org/en
https://projects.raspberrypi.org/en/pro ... -computing

Perhaps buy a book like "Programming the Raspberry Pi: Getting Started with Python" by Simon Monk.

This forum will be hear to help if you get stuck along your learning experience.
You can also investigate if there are and Raspberry Jams (Meetings of Pi users) or a hackspace in your area where people might be able or willing to help you if you need more hands on help.
Electronic and Computer Engineer
Pi Interests: Home Automation, IOT, Python and Tkinter

PhatFil
Posts: 448
Joined: Thu Apr 13, 2017 3:55 pm

Re: Pi ZeroW room thermometer

Thu Sep 20, 2018 2:30 pm

Welcome to the world of raspberry Pi, and congrats on the progress already made. What do you mean you know nothing, You have already programmed your Pi to read the temperature and display it.80-90% there!!. MOST PROGRAMMING INVOLVES A LOT OF CUT N PASTE, why reinvent the wheel is a very common truism..

A quick glance at your links tells me your using python which is a great place to start programming , and there are specific python forums that specialise in helping beginners and experts alike.. https://python-forum.io/ for example..

A python solution to regular temp readings and display updates could be to use a loop in your python program to read the temp display the result and wait 5 minutes. check out the while statement or the for statement ;)
https://www.google.co.uk/search?q=pytho ... &ie=UTF-8
A Pi solution would be to keep the program a simple single read, display and terminate sequence, and use the Pi system specifically the crontab feature to run your python script at regular intervals..
https://www.raspberrypi.org/documentati ... ge/cron.md
(hint https://crontab.guru/ )

pcmanbob
Posts: 4355
Joined: Fri May 31, 2013 9:28 pm
Location: Mansfield UK

Re: Pi ZeroW room thermometer

Thu Sep 20, 2018 3:09 pm

Hi staffyman.

When asking for one on one or handholding help its always a good idea to update your forum profile to include your location, at lease a country and which part of it your are in.

As you already have both the screen and your temperature sensor working , its now just a case of adding the 2 programs together so that you can read the sensor and then output the reading on the display ,
depending how often you intend to update the display you could loop your program so it waits for a set time after each each temperature reading, or if its going to be minutes then using cron to run your program at the required interval might be a better option.

There is a write up on using cron in this months magpi ( no. 73 ) on page 54.

If you post your code I will try and guide you on how best to combine your temperature reading and screen updated in to one program.

please use code tags when posting code as python re;lies on indentation for it operation.

Add [code] at the top

code goes here

and [/code] at the bottom.
Remember we want information.......................no information no help
The use of crystal balls & mind reading is not supported

staffyman
Posts: 7
Joined: Thu Sep 20, 2018 11:04 am
Location: Doncaster, South Yorkshire

Re: Pi ZeroW room thermometer

Thu Sep 20, 2018 5:09 pm

Thanks for the pointers and advice guys, I'll do some reading before reporting back and letting you all know how I get on.

User avatar
neilgl
Posts: 196
Joined: Sun Jan 26, 2014 8:36 pm
Location: Near Aston Martin factory

Re: Pi ZeroW room thermometer

Thu Sep 20, 2018 5:45 pm

Maybe do what I do - add entries into cron that run your scripts (in my case perl and shell scripts) that log temperature every 5 minutes
e.g. add cron entries (two) to log the temp and create the graphs:

Code: Select all

crontab -e
*/5 * * * * /home/neil/ngio/temp/templog.pl
*/5 * * * * /home/neil/ngio/temp/graph_temp.sh
save and exit

pcmanbob
Posts: 4355
Joined: Fri May 31, 2013 9:28 pm
Location: Mansfield UK

Re: Pi ZeroW room thermometer

Thu Sep 20, 2018 6:14 pm

Well Doncaster is not that far away from Mansfield so if you get really stuck it's not inconceivable that we could meet up in person.

Actual hand holding is not compulsory :D :lol:
Remember we want information.......................no information no help
The use of crystal balls & mind reading is not supported

staffyman
Posts: 7
Joined: Thu Sep 20, 2018 11:04 am
Location: Doncaster, South Yorkshire

Re: Pi ZeroW room thermometer

Sun Sep 30, 2018 10:42 am

So, I've made some progress with the build.

Bought myself a new soldering iron to replace the prehistoric relic I had in the shed. I now have an adjustable heat iron with a fine tip for doing delicate joints. I'm really pleased how I can now do neat joints instead of placing big blobs of solder and burning the circuit board like I used to. :?

I had the old soldering iron for years and very rarely used it. I want to keep using my new one!

But, I'm not posting this to rabbit on about my new found improved soldering skills but to show you how I'm progressing with this project.

So without further ado:

Image

Image

Image

Image

I've ran the existing Adafruit code to confirm everything works and I'd not wired up wrong or burnt any of the components.

I'm currently studying the Adafruit codes for both the AM2302 and the SSD1306 and going to attempt to merge them to achieve my goal. I've looked at some online tutorials but I just get confused. :oops:

I was the same back in my youth when we all had Spectrums, C64s etc and using BASIC. I couldn't get my head round that either.

I have a feeling this may take a while but am going to stick with it and report back again soon. Hopefully with good results. :)

User avatar
bensimmo
Posts: 3219
Joined: Sun Dec 28, 2014 3:02 pm
Location: East Yorkshire

Re: Pi ZeroW room thermometer

Sun Sep 30, 2018 11:12 am

We had a chap and his some come up to the HullPiJam this month as there was no Jam near him, ours was part of the Hull Science Festival.
There is one at Leeds too (Huddersfield and Manchester too).
Not sure if Sheffield has one, they should do as the good ship Pimoroni sails from there.
Don't think Scunny has one either.

Your more than welcome to pop along to the Hull one whenever we next have it. (there may or may not be a MakerSpace available for use too.)

staffyman
Posts: 7
Joined: Thu Sep 20, 2018 11:04 am
Location: Doncaster, South Yorkshire

Re: Pi ZeroW room thermometer

Sun Oct 14, 2018 1:22 pm

So I've decided to enroll in an online course to try and get my head around Python.
I've looked at the existing codes for the AM2302 and the SSD1306 and cobbled together what I thought would work but it doesn't, giving me an error of :
"Traceback (most recent call last):
File "test.py", line 88, in <module>
draw.text((x, top), "Room Temp =" + temperature, font=font, fill=255)
TypeError: cannot concatenate 'str' and 'float' objects"

Hopefully I've listed the code I cobbled together correctly:

Code: Select all

# Copyright (c) 2014 Adafruit Industries
# Author: Tony DiCola
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import time

import Adafruit_GPIO.SPI as SPI
import Adafruit_SSD1306
import Adafruit_DHT

from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont

# Raspberry Pi pin configuration:
RST = 24
sensor = Adafruit_DHT.AM2302
pin = 4

# Note the following are only used with SPI:
DC = 23
SPI_PORT = 0
SPI_DEVICE = 0

# 128x32 display with hardware I2C:
disp = Adafruit_SSD1306.SSD1306_128_32(rst=RST)

# 128x64 display with hardware I2C:
# disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST)

# Initialize library.
disp.begin()

# Clear display.
disp.clear()
disp.display()

# Create blank image for drawing.
# Make sure to create image with mode '1' for 1-bit color.
width = disp.width
height = disp.height
image = Image.new('1', (width, height))

# Get drawing object to draw on image.
draw = ImageDraw.Draw(image)

# Draw a black filled box to clear the image.
draw.rectangle((0,0,width,height), outline=0, fill=0)

# Draw some shapes.
# First define some constants to allow easy resizing of shapes.
padding = -2
top = padding
bottom = height-padding

# Move left to right keeping track of the current x position for drawing shapes.
x = 0

# Load default font.
font = ImageFont.load_default()

while True:

    # Draw a black filled box to clear the image.
    draw.rectangle((0,0,width,height), outline=0, fill=0)

    # Try to grab a sensor reading.  Use the read_retry method which will retry up
    # to 15 times to get a sensor reading (waiting 2 seconds between each retry).
    humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)

    # Write lines of text.
    draw.text((x, top),    "Room Temp =" + temperature,  font=font, fill=255)
    draw.text((x, top+20), "Humidity =" + humidity,  font=font, fill=255)

# Display image.
disp.image(image)
disp.display()



User avatar
bensimmo
Posts: 3219
Joined: Sun Dec 28, 2014 3:02 pm
Location: East Yorkshire

Re: Pi ZeroW room thermometer

Sun Oct 14, 2018 2:13 pm

File "test.py", line 88, in <module>
draw.text((x, top), "Room Temp =" + temperature, font=font, fill=255)
TypeError: cannot concatenate 'str' and 'float' objects"


that's saying it cannot stick together a string (str) and a number (float) in the line above.

So given it is text (from draw.text ) I guess it all wants to be in text ( a string).
So try replacing temperature for str(temperature) that should convert the number into a text string.

you should be able to spot and/or fix the next error about to happen too.

staffyman
Posts: 7
Joined: Thu Sep 20, 2018 11:04 am
Location: Doncaster, South Yorkshire

Re: Pi ZeroW room thermometer

Mon Oct 15, 2018 9:27 am

Thanks bensimmo, I've substituted temperature for str(temperature) and also the same on the line below with humidity.
Now when I set it running with the command sudo python thermometer.py it appears to run as the cursor just sits there blinking with no errors.

However, the screen stays blank. :?

Any suggestions :?:

I have received my email this morning for the online beginners course and will be checking that out when I have more time - too busy today what with work etc.. :cry:

scotty101
Posts: 3100
Joined: Fri Jun 08, 2012 6:03 pm

Re: Pi ZeroW room thermometer

Mon Oct 15, 2018 10:39 am

In your code you have an infinite loop "while True", This will keep running until you stop your code.

The two lines of code that actually display the image on the screen aren't in this loop so they never get executed and nothing is ever displayed on the screen.

Try changing your code the following (I've never used the Adafruit screen so this might not be correct)

Code: Select all

while True:

    # Draw a black filled box to clear the image.
    draw.rectangle((0,0,width,height), outline=0, fill=0)

    # Try to grab a sensor reading.  Use the read_retry method which will retry up
    # to 15 times to get a sensor reading (waiting 2 seconds between each retry).
    humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)

    # Write lines of text.
    draw.text((x, top),    "Room Temp =" + temperature,  font=font, fill=255)
    draw.text((x, top+20), "Humidity =" + humidity,  font=font, fill=255)

    # Display image.
    disp.image(image)
    disp.display()
    
    #Sleep for 1 second before redrawing the screen
    time.sleep(1)
You'll also need to add the following to the top of your file

Code: Select all

import time
Electronic and Computer Engineer
Pi Interests: Home Automation, IOT, Python and Tkinter

staffyman
Posts: 7
Joined: Thu Sep 20, 2018 11:04 am
Location: Doncaster, South Yorkshire

Re: Pi ZeroW room thermometer

Mon Oct 15, 2018 9:00 pm

Thank you so much bensimmo and scotty101, that did the trick. :D

Image

One more thing if you could be so kind.

How do I get it to display to just one decimal point and then add a "*C" after the temp reading and "%" after humidity?

User avatar
bensimmo
Posts: 3219
Joined: Sun Dec 28, 2014 3:02 pm
Location: East Yorkshire

Re: Pi ZeroW room thermometer

Tue Oct 16, 2018 7:43 am

https://www.tutorialspoint.com/python3/number_round.htm

Rounding function


"Humidity =" + round(humidity,1) + "%"

scotty101
Posts: 3100
Joined: Fri Jun 08, 2012 6:03 pm

Re: Pi ZeroW room thermometer

Tue Oct 16, 2018 8:55 am

bensimmo wrote:
Tue Oct 16, 2018 7:43 am
https://www.tutorialspoint.com/python3/number_round.htm

Rounding function


"Humidity =" + round(humidity,1) + "%"
You could do that. Or you could format the string to only show 1 decimal place for which there are more pythonic methods. Likewise their are better ways of formatting strings rather than using the + operator to add two together.

For example

Code: Select all

import math
print(f"Pi to one decimal place is {math.pi:.1f}")
This uses f-strings which are supported by python 3.6 and above.
For older versions you can use

Code: Select all

print("Pi to one decimal place is {0:.1f}".format(math.pi))

So in your code, you could use

Code: Select all

draw.text((x, top),    f"Room Temp ={temperature:.1f}*C",  font=font, fill=255)
draw.text((x, top+20), f"Humidity ={humidity:.1f}%",  font=font, fill=255)
OR

Code: Select all

draw.text((x, top),    "Room Temp ={0:.1f}*C".format(temperature),  font=font, fill=255)
draw.text((x, top+20), "Humidity ={0:.1f}%".format(humidity),  font=font, fill=255)
Electronic and Computer Engineer
Pi Interests: Home Automation, IOT, Python and Tkinter

User avatar
bensimmo
Posts: 3219
Joined: Sun Dec 28, 2014 3:02 pm
Location: East Yorkshire

Re: Pi ZeroW room thermometer

Tue Oct 16, 2018 10:39 am

Absolutely, just rounding is easier to understand at the start, the downside is it doesn't keep the 1dp if I remember correctly.
That and I can't remember .format of the top of my head.

So many ways,do whichever you find easiest :-)

But do eventually learn 'formatting', even if it make the code harder to read (in my opinion).
We're still at 3.5 in Raspbian so you'll need to use the pre 3.6 method :-)
Good to know the new methods and I need to spend some time learning it better

Any good cheat sheets?

Perhaps a good RPF tutorial on it?
Last edited by bensimmo on Tue Oct 16, 2018 10:42 am, edited 1 time in total.

staffyman
Posts: 7
Joined: Thu Sep 20, 2018 11:04 am
Location: Doncaster, South Yorkshire

Re: Pi ZeroW room thermometer

Tue Oct 16, 2018 10:41 am

Code: Select all

draw.text((x, top),    "Room Temp ={0:.1f}*C".format(temperature),  font=font, fill=255)
draw.text((x, top+20), "Humidity ={0:.1f}%".format(humidity),  font=font, fill=255)
This one worked. :D

Image

I changed my mind about the interval for taking the readings and made it every 10 seconds and not every 5 minutes as originally planned so that it is almost always a 'live' readout.

And then so it runs every time the Pi is booted I looked up how to add to cron and it really was easier than I expected.

I can't thank everybody enough for your help, I think my son will be extremely happy when he gets home from school and sees this working.

I suppose for any other person who is new to the world of Pi, coding with Python and has the same idea my son and I had, it would only be right to include the finished code below.

Code: Select all

# Copyright (c) 2014 Adafruit Industries
# Author: Tony DiCola
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import time

import Adafruit_GPIO.SPI as SPI
import Adafruit_SSD1306
import Adafruit_DHT

from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont

# Raspberry Pi pin configuration:
RST = 24
sensor = Adafruit_DHT.AM2302
pin = 4

# Note the following are only used with SPI:
DC = 23
SPI_PORT = 0
SPI_DEVICE = 0

# 128x32 display with hardware I2C:
disp = Adafruit_SSD1306.SSD1306_128_32(rst=RST)

# 128x64 display with hardware I2C:
# disp = Adafruit_SSD1306.SSD1306_128_64(rst=RST)

# Initialize library.
disp.begin()

# Clear display.
disp.clear()
disp.display()

# Create blank image for drawing.
# Make sure to create image with mode '1' for 1-bit color.
width = disp.width
height = disp.height
image = Image.new('1', (width, height))

# Get drawing object to draw on image.
draw = ImageDraw.Draw(image)

# Draw a black filled box to clear the image.
draw.rectangle((0,0,width,height), outline=0, fill=0)

# Draw some shapes.
# First define some constants to allow easy resizing of shapes.
padding = -2
top = padding
bottom = height-padding

# Move left to right keeping track of the current x position for drawing shapes.
x = 0

# Load default font.
font = ImageFont.load_default()

while True:

    # Draw a black filled box to clear the image.
    draw.rectangle((0,0,width,height), outline=0, fill=0)

    # Try to grab a sensor reading.  Use the read_retry method which will retry up
    # to 15 times to get a sensor reading (waiting 2 seconds between each retry).
    humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)

    # Write lines of text.
    draw.text((x, top),    "Room Temp = {0:.1f}*C".format(temperature),  font=font, fill=255)
    draw.text((x, top+20), "Humidity = {0:.1f}%".format(humidity),  font=font, fill=255)

    # Display image.
    disp.image(image)
    disp.display()

    #Sleep for 10 seconds before redrawing the screen
    time.sleep(10)

Return to “Beginners”

Who is online

Users browsing this forum: Taranuka and 37 guests