Silicon ChipRaspberry Pi Temperature/Humidity/Pressure Monitor Pt.1 - January 2016 SILICON CHIP
  1. Outer Front Cover
  2. Contents
  3. Publisher's Letter: QuickBrake: an idea whose time has come
  4. Feature: Blood Pulse Oximeters: How They Work by Jim Rowe
  5. Project: Raspberry Pi Temperature/Humidity/Pressure Monitor Pt.1 by Greg Swain
  6. Project: Valve Stereo Preamplifier For HiFi Systems by Nicholas Vinen
  7. Project: High Visibility 6-Digit LED GPS Clock, Pt.2 by Nicholas VInen
  8. Product Showcase
  9. Project: Reduce Rear-End Collision Risk With The QuickBrake by John Clarke
  10. Feature: Versatile Technology: An Aussie Innovator by Ross Tester
  11. Vintage Radio: Sony’s TR-63 shirt-pocket transistor radio by Ian Batty
  12. PartShop
  13. Feature: Handy Reactance Wallchart by Leo Simpson
  14. Market Centre
  15. Advertising Index
  16. Subscriptions
  17. Outer Back Cover

This is only a preview of the January 2016 issue of Silicon Chip.

You can view 39 of the 96 pages in the full issue, including the advertisments.

For full access, purchase the issue for $10.00 or subscribe for access to the latest issues.

Items relevant to "Raspberry Pi Temperature/Humidity/Pressure Monitor Pt.1":
  • Scripts for Raspberry Pi Temperature/Humidity/Pressure Monitor Pt.1 (Software, Free)
Articles in this series:
  • Raspberry Pi Temperature/Humidity/Pressure Monitor Pt.1 (January 2016)
  • Raspberry Pi Temperature/Humidity/Pressure Monitor Pt.1 (January 2016)
  • Raspberry Pi Temperature/Humidity/Pressure Monitor, Pt.2 (February 2016)
  • Raspberry Pi Temperature/Humidity/Pressure Monitor, Pt.2 (February 2016)
  • 1-Wire Digital Temperature Sensor For The Raspberry Pi (March 2016)
  • 1-Wire Digital Temperature Sensor For The Raspberry Pi (March 2016)
Items relevant to "Valve Stereo Preamplifier For HiFi Systems":
  • Stereo Valve Preamplifier PCB [01101161] (AUD $15.00)
  • STFU13N65M2 650V logic-level Mosfet (Component, AUD $10.00)
  • Red & White PCB-mounting RCA sockets (Component, AUD $4.00)
  • Dual gang 50kΩ 16mm logarithmic taper potentiometer with spline tooth shaft (Component, AUD $5.00)
  • Hard-to-get parts for Stereo Valve Preamplifier (Component, AUD $30.00)
  • Hifi Stereo Valve Preamplifier clear acrylic case pieces (PCB, AUD $20.00)
  • Stereo Valve Preamplifier PCB pattern (PDF download) [01101161] (Free)
  • Laser cutting artwork and drilling diagram for the Hifi Stereo Valve Preamplifier (PDF download) (Panel Artwork, Free)
Articles in this series:
  • Valve Stereo Preamplifier For HiFi Systems (January 2016)
  • Valve Stereo Preamplifier For HiFi Systems (January 2016)
  • Valve Stereo Preamplifier For HiFi Systems, Pt.2 (February 2016)
  • Valve Stereo Preamplifier For HiFi Systems, Pt.2 (February 2016)
Items relevant to "High Visibility 6-Digit LED GPS Clock, Pt.2":
  • High Visibility 6-Digit LED GPS Clock PCB [19110151] (AUD $15.00)
  • PIC32MX170F256B-I/SP programmed for the High Visibility 6-Digit LED GPS Clock [1911015D.HEX] (Programmed Microcontroller, AUD $15.00)
  • MCP1700 3.3V LDO (TO-92) (Component, AUD $2.00)
  • VK2828U7G5LF TTL GPS/GLONASS/GALILEO module with antenna and cable (Component, AUD $25.00)
  • Six 70mm tall 7-segment displays, BLUE plus four matching diffused 5mm LEDs (Component, AUD $40.00)
  • Six 70mm tall 7-segment displays, EMERALD GREEN plus four matching 5mm LEDs (Component, AUD $50.00)
  • Six 70mm tall 7-segment displays, HIGH BRIGHTNESS RED plus four matching diffused 5mm LEDs (Component, AUD $25.00)
  • Six 70mm tall 7-segment displays, GREEN plus four matching diffused 5mm LEDs (Component, AUD $30.00)
  • Blue 5mm LED with diffused lens (25mm leads) (Component, AUD $0.20)
  • Blue 5mm LED with diffused lens (15mm leads) (Component, AUD $0.20)
  • 40109B level shifter IC (DIP-16) (Component, AUD $2.00)
  • High Visibility 6-Digit LED GPS Clock acrylic case pieces - CLEAR (PCB, AUD $20.00)
  • High Visibility 6-Digit LED GPS Clock acrylic case pieces - BLUE TINTED (PCB, AUD $25.00)
  • High Visibility 6-Digit LED GPS Clock acrylic case pieces - GREEN TINTED (PCB, AUD $25.00)
  • High Visibility 6-Digit LED GPS Clock acrylic case pieces - RED TINTED (PCB, AUD $25.00)
  • Firmware (HEX) file and C source code for the High Visibility 6-Digit LED GPS Clock [1911015D.HEX] (Software, Free)
  • High Visibility 6-Digit LED GPS Clock PCB pattern (PDF download) [19110151] (Free)
  • High Visibility 6-Digit LED GPS Clock case cutting diagram (download) (Software, Free)
Articles in this series:
  • High Visibility 6-Digit LED GPS Clock (December 2015)
  • High Visibility 6-Digit LED GPS Clock (December 2015)
  • High Visibility 6-Digit LED GPS Clock, Pt.2 (January 2016)
  • High Visibility 6-Digit LED GPS Clock, Pt.2 (January 2016)
Items relevant to "Reduce Rear-End Collision Risk With The QuickBrake":
  • QuickBrake/Delta Throttle Timer PCB [05102161] (AUD $12.50)
  • QuickBrake/Delta Throttle Timer PCB pattern (PDF download) [05102161] (Free)
Articles in this series:
  • Reduce Rear-End Collision Risk With The QuickBrake (January 2016)
  • Reduce Rear-End Collision Risk With The QuickBrake (January 2016)
  • Delta Throttle Timer For Cars (March 2016)
  • Delta Throttle Timer For Cars (March 2016)
Items relevant to "Handy Reactance Wallchart":
  • Giant Reactance Wallchart (A2), folded (Back Issue, AUD $10.00)

Purchase a printed copy of this issue for $10.00.

Monitor temperature, humidity & pressure using a Raspberry Pi & Sense HAT module Want to be able to monitor temperature, humidity and pressure using a web browser from a remote location? Here’s how to do it using a Raspberry Pi 2 Model B computer, a plug-in Sense HAT module, a Wi-Pi WiFi dongle and an 8GB microSD card. W HAT’S A Raspberry Pi? If you’ve been sleeping and missed all the hype, then no, it’s not something that four and twenty blackbirds are baked in. Instead, it’s a $40 credit-card-size single-board computer boasting a 900MHz quad-core ARM Cortex-A7 CPU, a VideoCore IV multimedia coprocessor, 1GB of on-board RAM, a micro-SD card slot and a full HDMI port to output video and sound to a monitor or TV. 18  Silicon Chip Also on-board are four USB ports, an Ethernet port, a 40-pin GPIO (general-purpose input/output) port, a camera interface, a display interface and a combined 3.5mm audio & composite video jack. It’s powered from a 5V plugpack and runs a cut-down Linux operating system such as Raspbian, RaspBMC, Arch Linux or OpenELEC. We’re using the Raspberry Pi here with a Sense HAT siliconchip.com.au This view shows the Raspberry Pi with the Sense HAT module plugged into its GPIO port & a Wi-Pi dongle connected to one of its USB ports. desktop on another computer (eg, a Windows PC), so that it can be controlled using the remote PC’s keyboard and mouse. That’s all described below in Pt.1 this month. We’ll follow on next month by showing you how to stream the Sense HAT sensor readings to a web server, so that you can access them using a browser over the internet. That’s done by installing Apache Web Server and copying across the necessary software program which we’ll make available on our website. Sense HAT module & Wi-Pi Pt.1: By Greg Swain multi-sensor module to form a basic temperature, humidity and pressure monitor. There’s no soldering involved – it’s just a matter of plugging everything together and bashing a keyboard for an hour or so to set it up. We’re going to start by showing you how to get your own Raspberry Pi running by installing (and configuring) the Raspbian operating system. We’re then going to describe how to connect it to your WiFi network before moving on to retrieving the various readings from the Sense HAT module using some simple Python scripting programs. We’re also going to show you how you can run the Raspberry Pi “headless”; ie, no keyboard, mouse or monitor. That’s done by using an application called TightVNC. This lets you display your Raspberry Pi’s siliconchip.com.au As mentioned, a Raspberry Pi Sense HAT module is one of the major components in this project. It plugs directly into the Raspberry Pi’s 40-pin GPIO port and carries an impressive array of on-board goodies. These include: • A temperature and humidity sensor; • An air-pressure sensor; • An accelerometer, gyroscope and magnetometer; • An 8x8 LED matrix display; and • A miniature joystick We’ll just be using the temperature, humidity and airpressure sensors here but there’s nothing to stop you from experimenting with the remaining sensors, as detailed on various internet sites (Google is your friend). The other major part used in our system is a Wi-Pi WiFi dongle. This $10 part connects to one of the Raspberry Pi’s USB ports and frees the unit from a wired network connection. It works straight out of the box (more on this later). The Edimax EW-7811Un WiFi dongle is also compatible with the Raspberry Pi and there are others, as a Google search will reveal. Note, however, that many WiFi dongles are not directly supported by Raspbian although it may be possible to get them going by downloading and installing suitable drivers. However, that can be an exercise in frustration unless you’re a real Linux expert. In addition, many dongles draw more USB power than can be supplied by the Raspberry Pi and so would need to be run via a powered USB hub. For minimum hassle, we suggest you stick to either the Wi-Pi or the Edimax EW-7811Un (see parts list panJanuary 2016  19 Fig.1: if necessary, the microSD card can be formatted using the freeware SDFormatter utility. Set the Format Type & Format Size Adjustment options as shown. el). Alternatively, you can dispense with WiFi set-up if a wired network connection is convenient. What else is needed? As well as the above parts, you’ll also need a 5V 1A plugpack fitted with a micro-USB connector to power the system and an 8GB (up to 32GB) microSD card. If you’ve owned an Android smartphone, then you probably already have a suitable plugpack with a 5V USB output lying around. You may even have the correct USB to micro-USB cable; if not, you can pick one up for a few dollars. The microSD card functions as the Raspberry Pi’s boot disk. It holds the Raspbian operating system and should preferably be a class 10 type, although a class 6 card will do the job. You’ll also initially need these parts to set up the unit: a USB keyboard and mouse (wireless units are OK), an HDMI cable, a monitor and a USB memory card reader. If you don’t have a spare keyboard, mouse or monitor, you can temporarily borrow them from your main PC for the setting-up procedure. Once the set-up has been completed, the unit can be run “headless”; ie, without the keyboard, mouse and monitor. The card reader is required only to install the operating system to the microSD card. OK, here’s how to install Raspbian and set up the system for temperature measuremernts: Step 1: Install Raspbian Once you have all the parts, the first step is to install the Raspbian OS on the microSD card. It’s just a matter of pointing your PC’s web browser to the Raspberry Pi Foundation’s website at https://www.raspberrypi.org/ downloads and following the instructions. If you intend pressing a pre-used microSD card into service, then it’s a good idea to format it first. Begin by downloading the SD Card Formatter utility (from https://www.sdcard.org/downloads/formatter_4/), then unzip the file and install it on your PC. You then launch the utility and format the microSD card (to FAT32) using the Full Overwrite option and with the Format Size 20  Silicon Chip Adjustment option set to ON (Fig.1) – see https://www. raspberrypi.org/documentation/installation/noobs.md On the other hand, if you have a new microSD card, this will come pre-formatted, so you can skip the formatting procedure. As indicated on the website, there are two ways to go about installing the Raspbian OS: (1) using the zipped image file; or (2) using NOOBS. If you elect to use method 1, begin by downloading the zipped Raspbian image file to your PC (Raspbian Jessie is the latest version as this is being written). This is a 1.3GB zip file, so it will take an hour or so to download with an ADSL2 or cable connection. Once the download is complete, unzip the file to recover the 4.3GB image file. The next step is to write the Raspbian OS to the micro-SD card using an image writing tool – see https:// www.raspberrypi.org/documentation/installation/installing-images/README.md This website has instructions for PC, Mac and Linux operating systems. If you’re using a Windows PC, you will have to download and install the Win32 Disk Image utility (available from http://sourceforge.net/projects/win32diskimager/). You then simply launch the utility, select the unzipped image file, choose the drive to write the image to and click the write button (see Fig.2); the utility then does the rest. Be sure to chose the correct drive to write the image to, otherwise you could lose valuable data. By contrast, both Mac and Linux systems use the inbuilt “dd” command line utility. Just follow the instructions on the website. Step 2: The NOOBS alternative Method 2 involves first downloading NOOBS (New Out Of the Box Software), also found at https://www. raspberrypi.org/downloads/ This is a 983MB download and again comes down as a zip file. You then simply copy the unzipped files to the micro-SD card (no image file writer is need), as described in the included readme file. NOOBS is basically an easy operating system installer. Its advantage is that it makes it easy to install alternative operating systems the first time it’s started. Only Raspbian is included in NOOBS though; the others are downloaded and installed from the internet. Step 3: Fire up the RPi Now to get Raspbian running on the Pi. Plug in your keyboard, mouse and monitor cables but leave the Sense HAT and the Wi-Pi dongle to one side for the time being. That done, insert the microSD card in the Pi’s card reader, turn on the monitor and plug the USB power cable into the micro-USB connector. The Raspberry Pi will begin to boot as soon as power Fig.2: use Win32 Disk Imager to write the Raspbian image file to the microSD card (Windows PCs only). siliconchip.com.au The Sense HAT module (right) plugs directly into the Raspberry Pi 2 Model B computer’s 40-pin GPIO port. is applied. If you’ve written an image file to the microSD card, Raspbian should boot straight to the graphical user interface (GUI). Alternatively, if you’ve used NOOBS, a window will appear prompting you to install the operating system – just tick the box next to Raspbian and click the Install button. The system should then boot to the GUI. If it doesn’t, just type startx to launch the GUI. The default username is pi, while the default password is raspberry (although by default, it should not prompt you for these). Step 4: Configure it The next step is to configure the system for your location, timezone and keyboard. In particular, the default keyboard configuration is for the UK and it can give the wrong characters in some cases; eg, an “<at>” character when double quotes are entered. Begin by clicking Menu -> Preferences -> Raspberry Pi Configuration, then click the Localisation tab on the resulting dialog box. You can then Set your Locale (leave the Character Set at UTF-8) and the Timezone. Ignore the Set Keyboard button; there’s a bug in this configuration utility and the keyboard setting doesn’t stick when you reboot. Fortunately, there’s an easy way around this and we’ll get straight to it. Having set the locale and the timezone, click the OK button and allow the system to reboot. Now for the keyboard configuration. Launch the Terminal (click on the taskbar icon at top left), then enter the command sudo raspi-config to launch the Software Configuration Tool. That done, select Internationalisation Options (they’ve got to be kidding!), then select Change Keyboard Layout. Next, select your keyboard type [eg, Generic 105-key (Intl) PC], then select “Other” from the following dialog. You then choose English (US), then use the Up arrow siliconchip.com.au You’ll Need These Parts Core parts 1 Raspberry Pi 2 Model B computer module . . . $48 from element14 1 Raspberry Pi Sense HAT module . . . $47.98 from element 14 1 Wi-Pi WiFi dongle . . . $9.31 from element14 (see text) 1 8-32GB micro-SD card (class 6 or class 10) . . . or purchase a pre-programmed micro-SD card from element14 or Wiltronics 1 5V 1A power supply with USB to micro-USB cable The parts required during set-up 1 USB keyboard and mouse (wireless units should work, provided they’re paired) 1 monitor with HDMI or DVI input 1 HDMI-HDMI or HDMI-DVI cable to suit monitor 1 microSD card reader Raspberry Pi starter packs If you don’t have any of the core parts, Wiltronics has a number of Raspberry Pi starter packs – see www. wiltronics.com.au These include: (1) A Basic Starter Pack consisting of a Raspberry Pi 2 Model B computer, a 5V power supply adaptor, a case and a pre-programmed (NOOBS) 8GB microSD card. (2) A Standard Starter Pack which includes the Basic Starter Pack parts and adds a 2-metre HDMI cable and a 3-metre Ethernet cable. (3) A Raspberry Pi 2 Model B WiFi Pack which includes the Basic Starter Pack parts plus a USB WiFi module (with whip antenna), a card reader and a 2-metre HDMI cable. key to scroll up to the English (US) option (again). Note that there must be no qualifying text after the English (US) listing. Next, tab to OK and then repeatedly press the Enter key to take you back to the opening menu of the SoftJanuary 2016  21 The Wi-Pi dongle plugs directly into one of the Pi’s USB ports and is easy to get going. ware Configuration Tool. Finally, use the tab key to select Finish, press Enter and that’s it – your keyboard is now configured. You can test this by opening the Leafpad text editor (Menu -> Accessories -> Text Editor) and typing the double quotes (“) symbol. If you get double quotes rather than an <at> symbol, then all is well. Step 5: Change the password As stated, the default username is “pi” and the default password is “raspberry”. You can keep the “pi” username but leaving the default password is never a good idea so the next step is to change it. That’s also done using the Software Configuration Tool. Just enter the command sudo raspi-config in the Terminal, choose Change User Password and follow the bouncing ball (well, not literally). Be sure to use a strong password and write it down in case you forget it. The Software Configuration Tool also allows you to choose various boot options. You can elect to boot straight to the Desktop GUI with automatic login (the default), to a Text console requiring a username and password, or to two other variations of these. Step 6: Get the WiFi going Getting the WiFi going is easy. First, shut down Raspbian, connect a Wi-Pi (or other compatible) WiFi dongle to a spare USB port and reboot (note: it’s necessary to boot the system with the Wi-Pi dongle connected. It won’t work if you connect it to a USB port after the system has started). During the boot process, the system automatically detects the Wi-Pi and installs the correct driver. Wait until the desktop GUI appears, then hover the mouse over the network icon on the taskbar at top right. A message will appear telling you that wlan0 is “Not associated”. Now click the network icon; it should be scanning for local APs (WiFi access points). Give it time to discover any local WiFi netFig.3: connect to your WiFi works, then select your network by selecting it and WiFi network from the list, enter your WiFi password entering the password. 22  Silicon Chip in the resulting dialog box and click OK. The Wi-Pi will then connect to your WiFi network and the networking icon on the taskbar will be replaced with the WiFi icon. That’s it; your WiFi connection will now be working. You can check this by launching the web browser (it’s the icon next to the Menu button) and entering in a web address. You will need to enter in the full http://www string in order to go direct to a website. If you just start with the address www, it will (annoyingly) search for the entry using the DuckDuckGo search engine. As an aside, when your WiFi password is entered as described above, the system places an entry for your network in the /etc/wpa_supplicant/wpa_supplicant.conf configuration file. The associated /etc/network/interfaces file is left completely unmodified by this process. If you have a second WiFi network that you connect to, its entry will also be placed into wpa_supplicant.conf (beneath the first entry) when you go through the above procedure – see Fig.4. Don’t get sucked into hand-fettling either of the above two configuration files as described in numerous online sites. Provided your WiFi network broadcasts its ssid (ie, network name), that’s not necessary under normal circumstances. With the WiFi working, it’s time for some updates and upgrades (these will take quite some time): sudo apt-get update sudo apt-get upgrade sudo reboot Step 7: The hidden WiFi fix What if your WiFi ssid is hidden by the router? That’s a somewhat different kettle of fish. In that case, you do have to manually edit the wpa_ supplicant.conf file and that’s best done using Raspbian’s Leafpad text editor (yes, you can use the Nano terminal editor but a GUI text editor is easier for anyone new to Linux). There’s just one precaution – you have to open Leafpad as a super user. Here’s what to do: (1) Click Menu -> Run and in the resulting dialog enter the command sudo leafpad (2) In Leafpad, click File -> Open -> File System, then navigate to the /etc/wpa_supplicant folder and open wpa_ supplicant.conf Fig.4: this wpa_supplicant.conf file has the details for two WiFi networks. Note that the scan_ssid=1 line must be manually added for a hidden network. siliconchip.com.au (3) There will already be two lines in this file. All you have to do is add the following lines, substituting your WiFi’s network name and password as appropriate (keep the double quotes and note the opening and closing parentheses): network={ ssid="YourWiFiNetworkName" scan_ssid=1 psk="YourWiFiPassword" key-mgmt=WPA-PSK } Save this file, then reboot the system; it should now connect to your hidden WiFi network. Fig.4 shows an example wpa_supplicant.conf file. In this case, two WiFi networks are present (one for home and one for work). Note the scan_ssid=1 entry in the first network; this line is necessary only if the WiFi network is hidden and should immediately follow the ssid= "YourWiFiNetworkName" line. By the way, there’s a quick way of configuring wpa_supplicant.conf if you have a hidden network. Start by clicking on the networking icon on the taskbar, then select any one of the detected WiFi networks and enter a false password into the resulting dialog. It’s then just a matter of opening wpa_supplicant.conf (sudo leafpad), editing the network name and password and inserting scan_ssid=1 directly under ssid="YourWiFiNetworkName". Alternatively, you could temporarily un-hide your WiFi’s SSID (via your router’s web interface), connect it to the network as described above, and then hide it again. It would then just be a matter of inserting the scan_ssid line in wpa_supplicant.conf and rebooting. Once it’s working, update and upgrade the system as described at the end of the previous section. Step 8: Connect the Sense HAT With the WiFi now working, it’s time to connect the Sense HAT. Before plugging it in, connect a couple of M3 x 12mm Nylon spacers to the mounting holes on the opposite side of the header. This step is necessary to ensure that the otherwise unsupported edge of the module cannot be pushed down onto the Pi’s HDMI socket. Note that it will be necessary to enlarge the mounting holes to 3mm before attaching the spacers (the module comes with 2.5mm mounting holes). Do this carefully with a low-speed drill, to avoid damage to adjacent tracks and parts on the Sense HAT. Once the spacers are in place, power down the Raspberry Pi, plug the Sense HAT module into the GPIO port and reboot. The Sense HAT software is then installed from the Terminal, as follows: sudo apt-get install sense-hat sudo pip-3.2 install pillow sudo reboot It’s now time to check that the Sense HAT is working and will respond to a simple program entered into siliconchip.com.au Fig.5: this is the output that appears in Python when running the simple temperature reading program at the bottom of this column. Python 3, a high-level scripting language that comes with Raspbian. Start by opening Python 3 as sudo from a terminal window by entering the command: sudo idle3 & Wait until the Python 3 Shell dialog opens, then open a new window by clicking File -> New File and enter in the following code: from sense_hat import SenseHat sense = SenseHat() sense.show_message("It Works!") Save the file into the default /home/pi folder (eg, as Message.py), then click Run -> Run Module. You should see the “It Works” message (without the quotes) scroll through on the Sense HAT’s LED matrix display. Step 9: Retrieving sensor readings Temperature, humidity and pressure readings can be retrieved from the Sense HAT using the following Python code lines: temp = sense.get_temperature() humidity = sense.get_humidity() pressure = sense.get_pressure() Let’s write a simple program to display the temperature. Open up a new window in Python (File -> New File) and insert the following lines: from sense_hat import SenseHat sense = SenseHat() sense.clear() temp = sense.get_temperature() temp = round(temp, 1) print("Temperature =",temp) Save this file (eg, as Environment1.py), then click Run -> Run Module. You should see an output in the Python 3 Shell window like that shown in Fig.5. Note the temp = round(temp, 1) line; this rounds the reading to one decimal place. Now that you have that running, let’s add some extra code to measure humidity and air pressure as well. In addition, we’ll add some extra code so that the readings January 2016  23 Fig.6: this is the output that appears when running the more complicated code shown below. You stop the program by typing Ctrl-C. are repeated every five seconds. The code is as follows (be sure to include tabs, as shown): from sense_hat import SenseHat import time sense = SenseHat() sense.clear() while True: temp = sense.get_temperature() temp = round(temp, 1) print("Temperature =",temp) humidity = sense.get_humidity() humidity = round(humidity, 1) print("Humidity =",humidity) pressure = sense.get_pressure() pressure = round(pressure, 1) print("Pressure =",pressure) print() time.sleep(5) The while True: statement puts the program into a loop (so that the readings are repeated), while the time.sleep(5) statement repeats the readings every five seconds. Note that the lines following the while True: statement must be tabbed by the same amount, as shown. In addition, the import time statement must also be added near the top of the file, to import the time library. When you run this program, the output will be as shown in Fig.6. Step 10: Correct the temperature If the system has been on for some time, the first thing you’ll notice about the temperature readings is that they are too high, typically by 10°C or more. That’s due to the readings being skewed by heat from the Raspberry Pi module. Basically, the temperature 24  Silicon Chip sensor measures the temperature of the Sense HAT’s PCB and this is soaking up heat from the Raspberry Pi module, particularly if it’s been on for some time and is running at its full operating temperature. A lot of the Pi’s heat is generated by the ARM7 processor which typically runs somewhere around 44-47°C when the ambient air temperature is 25°C, with additional heat input from the graphics co-processor. The end result is that the Sense HAT’s temperature sensor is measuring the system temperature rather than the ambient air temperature, particularly if the two modules are enclosed in the same case. So what can be done about this? One obvious answer it to physically separate the two modules, preferably using an extension cable. Unfortunately, a 2x20-pin extension cable with a male header on one end and a female header at the other isn’t easy to come by. Another approach is to enclose the Raspberry Pi in a case and mount the Sense HAT module on top of this case, so that it’s shielded to some extent from the heat. The Sense HAT module then connects to the Pi’s GPIO pins via a stackable header that fits through a matching slot in the top of the case. That’s the approach we adopted for the final version of this project described next month. In addition, we’ve built a correction factor for the temperature readings into the Python script. Fairly obviously, the measured air temperature will sit somewhere between the true air temperature and the ARM7’s core temperature. Fortunately, the ARM CortexA7 CPU has an inbuilt temperature sensor and it only takes a few lines of code to retrieve the reading. So we can retrieve this reading and use it to compensate the temperature reading extracted from the Sense HAT’s onboard sensor. One source on the internet suggested that subtracting the measured temperature (t) from the ARM7’s core temperature (ct), halving this and then subtracting the result from the measured temperature would give an ambient temperature (ta) reading that was accurate to with a degree or two. In other words: ta = t - ((ct - t) x 0.5) So, for example, if the measured air temperature (t) was 35°C and ct was 47°C, then the calculated real ambient temperate (ta) would be 29°C. In practice, we found that this gave readings that are about 3°C too high at normal room temperatures, so we modified the equation as follows: ta = t - ((ct - t) x compensation) A compensation value of 0.8 rather than 0.5 when the two modules are stacked close together gives an ambient temperature that’s accurate to within about 1°C, at least for temperatures ranging from about 20°C to 35°C and with relatively steady ambient temperature. The Python program shown in the adjacent panel (Environment2.py) incorporates this modified equation, along with a few other enhancements. First, the code including and immediately following the def get_cpu_ temp() line retrieves the core temperature of the ARM7 siliconchip.com.au Environment2.py from sense_hat import SenseHat import time import os def get_cpu_temp(): t = os.popen('/opt/vc/bin/vcgencmd measure_temp') cpu_temp = t.read() t.close() cpu_temp = cpu_temp.replace('temp=','') cpu_temp = cpu_temp.replace('\'C\n','') return float(cpu_temp) sense = SenseHat() while True: t = 0 p = 0 h = 0 ct = 0 n = 5 for x in range(0, n): t += sense.get_temperature() p += sense.get_pressure() h += sense.get_humidity() ct += get_cpu_temp() time.sleep(0.5) t /= n p /= n h /= n ct /= n ta = round((t-(ct-t)*0.8),1) p = round(p,1) h = round(h,1) Fig.7: the Environment2.py code corrects for heat soak from the Raspberry Pi module by measure the Pi’s CPU temperature & introducing a compoensation factor. msg = "Temperature = %s, Pressure = %s, Humidity = %s" % (ta,p,h) print(msg) time.sleep(5) CPU. Then, rather than just take one measurement for each sensor, the program takes five measurements [n = 5] at 0.5 second intervals [time.sleep(0.5)] and then averages them [/= n] to get more accurate readings. It then calculates the temperature reading and rounds it to one decimal place using the equation ta = round((t – (ct – t)*0.8),1) and displays the results for temperature, pressure and humidity. This entire procedure is then repeated five seconds later [time.sleep(5)] for the next set of measurements. To save you typing it out (and risking errors), the Environment2.py program well be available for download from the SILICON CHIP website. By default, it will download into your /home/pi/downloads folder. You can move it from there into your /home/pi folder if desired. Fire up Python 3, open the file and run it. You should see a readout as shown in Fig.7. To stop the program, simply click anywhere in the Python Shell window (to make it active) and hit Ctrl-C on the keyboard. siliconchip.com.au You will need an accurate thermometer to calibrate the unit against. If the measured temperature is incorrect, adjust the value of the calibration factor in the Environment2.py listing. Note that you will have to leave the unit running for 30 minutes or so, until its operating temperature stablises, before getting accurate results. In addition, the selected compensation factor will likely only be valid over a fairly narrow range of temperatures (we haven’t had a chance to test this yet). It’s also important to note also that the humidity readings will also be affected by any localised heating but we haven’t corrected for this. Step 11: Run it headless By now, you’re probably wondering how you can run the whole shebang without a keyboard, mouse and monitor, especially if you’ve borrowed these parts for your main PC. That’s easily done using a program called TightVNC (VNC = Virtual Network Computing), as detailed in the following section. That’s all for now. Next month, we’ll describe how January 2016  25 Running It Headless Using TightVNC O NCE YOU’VE finished setting up the Raspberry Pi, you’ll want to operate it free of the keyboard, mouse and monitor. That way, you can place the Pi anywhere in a room (eg, on a bookshelf) with nothing more than the power cable from the plugpack running to it. However, it’s a good idea to first set it up so that you can control it using another computer. That way, you’ll be able to change settings and even cleanly shut it down if necessary. The best way to do this is to install a VNC (Virtual Network Computing) server on the Raspberry Pi. This will allow you to view the Pi’s desktop (or GUI) from a Windows, Mac or Linux PC. It’s also necessary to install a VNC viewer on the PC, to make the connection. The Pi’s desktop then appears as a separate window on the PC’s desktop and you have complete control. We’re using TightVNC for this project. It’s installed on the Raspberry Pi by opening the Terminal and issuing the command: sudo apt-get install tightvncserver When the installation is complete, start the server as follows: vncserver :1 -geometry 1280x800 -depth 24 The first time you do this, you’ll be asked to create a password which the PC user must use to connect to the Pi. This password should be limited to eight characters, otherwise it will be truncated (note that no characters will appear as you type the password). You’ll also be asked if you want to set a read-only password but that’s optional. Once that’s done, a message will confirm that the settings have been saved in /home/pi/.vnc and that virtual desktop 1 has been created, ie: New ‘X’ desktop is raspberrypi:1 We now want TightVNC to automatically start when the system is booted. To do that, launch sudo leafpad from the Terminal, create a new file called vncserver.service in /etc/ systemd/system and add the following code: Fig.8: you only need TightVNC Viewer on the remote PC, so deselect the server option during installation. You then need to change the file so that it is owned by root, make it executable and ensure it starts during boot as follows: sudo chown root:root /etc/systemd/system/vncserver.service sudo chmod 755 /etc/systemd/system/vncserver.service sudo systemctl enable vncserver.service Reboot the system (sudo reboot) to get it running correctly. Windows client The next step is to install a VNC client (or viewer) on your PC. If you are using a Windows computer, go to www. tightvnc.com and download the TightVNC software. Both 32-bit and 64-bit versions are available; be sure to choose the correct one for your version of Windows. Double-click the downloaded file to begin the installation process and choose the Custom option. You only need to install the viewer, so deselect [Unit] the TightVNC Server option description=Remote Desktop Server (see Fig.8), then click Next and After=syslog.target network.target deselect the firewall option in the following dialog. [Service] That done, complete the User=pi installation, then launch TightType=forking VNC Viewer (see Fig.10) and PAMName=login click the Options button to open ExecStart=/usr/bin/vncserver :1 -geometry 1280x800 -depth 24 the Connections Options dialog. Drag the Compression Level [Install] and JPEG sliders to “best” (you WantedBy=multi-user.target to install Apache Web Server so that you can access the sensor readings over the internet via a web browser. This will also allow you to change the compensation setting, alter the number of displayed readings and change the time interval between readings simply by 26  Silicon Chip entering the values at the end of the URL (web address). Finally, we intend to mount the Raspberry Pi in a clear Perspex case, with the Sense HAT module mounted on the outside and connected to the Pi via a stackable header to separate the two and minimise heat problems. siliconchip.com.au can adjust these back later to improve speed if necessary), then set the Mouse Cursor option to “Don’t show remote cursor” and the Local Cursor Shape to “Arrow”. The remaining options can stay at the defaults. Connecting to the Pi You’re now ready to connect to the Raspberry Pi from your Windows computer. All you have to do is launch TightVNC Viewer, enter the Pi’s IP address followed by :1 in the dialog and click Connect. For example, if the Pi’s IP address is 192.168.0.46, you would enter: 192.168.0.46:1 How do you know what the Pi’s IP address is? Simply hover the mouse over the WiFi icon on the Pi’s taskbar and it will tell you. Alternatively, issue the ifconfig command in a Fig.9: this screen grab shows the Raspbian desktop running in a TightVNC Terminal window and again the IP address for window on a Windows 10 PC. This gives you full remote control over the wlan0 (or eth0 if you’re using a wired Ethernet Raspberry Pi module. connection) will be listed. That’s it; you can now operate your Raspberry Pi without a Fig.10: you connect to the Pi from your mouse, keyboard or monitor. PC by typing in its If you’re using Linux on the remote computer, it will IP address followed probably already have a VNC client (Vinagre) installed. by “:1” (without the Alternatively, for a Mac, try VNC Viewer or use the inbuilt quotes). Screen Sharing app (Google it). Tidying up By default, you will not be able to copy and paste from any applications running in the Raspberry Pi window and any local applications on your PC. To fix that, you first need to install autocutsel using the command: sudo apt-get install autocutsel You then use the Nano text editor to modify the xstartup file in the hidden .vnc folder. That’s done by opening the file using nano /home/pi/.vnc/xstartup and inserting the line autocutsel -fork as follows: #!/bin/sh xrdb $HOME/.Xresources xsetroot -solid grey autocutsel -fork #x-terminal-emulator -geometry 80x24+10+10 -ls -title "$VNCDESKTOP Desktop" & #x-window-manager & # Fix to make GNOME work export XKL_XMODMAP_DISABLE=1 /etc/X11/Xsession Save this file (Ctrl-O) and restart the VNC server (reboot-ing the Raspberry Pi is the easiest way to do this). You will then be able to cut and paste between the two desktops on the PC. Another problem arises if you try to run a GUI application as root; ie, using sudo. This will immediately result in a message informing you that you are not authorised to connect. The way around this is to issue the command xhost + siliconchip.com.au in the Terminal. This gives all users access to the Raspberry Pi’s display or you can restrict root access to a particular user by using xhost + hostipaddress, where hostipaddress is the ip of the authorised user (eg, xhost + 192.168.0.10). How secure is it? TightVNC uses ports 5800 & 5900 to communicate with the outside world, so provided you keep these ports closed on your router, you should be safe from internet hacks. In short, don’t do it unless you use a very strong password. Even then, it’s a bit of a security risk since all traffic except for the password is unencrypted. The way around this is to install an SSH (secure shell) server and use an SSH tunnel for TightVNC connections (details next month). Fixed IP address Finally, by having the Raspberry Pi pick up its IP address from your router’s DHCP server, there’s always a risk that this IP can change if the power is interrupted. If that happened, you would no longer know the IP address when attempting to connect using TightVNC Viewer. A dynamic IP can also complicate matters when connecting to the Pi’s web server, especially over the internet. For this reason, it’s best to have the router issue a fixed IP address to the Raspberry Pi. We’ll show you how in Pt.2 next SC month. January 2016  27