Sunday, 16 September 2018

Using Desktop Raspbian with a second screen or projector

After various dalliances with Mint, Mate, Elementary and vanilla Ubuntu, we've decided to standardise on the Desktop version of Raspbian for the "club" laptops that we have available at CoderDojo Ham,

There's a couple of reasons for this. Firstly it installs easily and quickly, and runs well on old, low.  powered devices (most of our laptops are donated or re-furbished) . Secondly, it comes with loads of great educational software and editors installed be default, which saves time in preparing the machines for use.

An important part of our Dojo is the show-n-tell at the end, where the keen youngsters show off their amazing projects on the big screen. This is always hugely popular and we normally have a long queue of patient coders to get through.

One thong we hadn't thought about when selecting Desktop Raspbian as our operating system of choice was using the club machines with the AV desk and getting them to display on the Kingston University STEM centre's excellent big screens. The first time we connected the VGA cable to the port on one of the laptops, nothing appeared to happen, and none of the menu setting within Raspbian seemed to help. Obviously the look and feel of Raspbian is geared towards the Raspberry Pi, so using multiple displays is not a common configuration.

After some messing around we discovered that reboot the laptop allowed the projector to be detected, although the default setting seemed to be for 2 screens rather than having the second mirror the first.

This is OK, but rebooting takes up precious time (remember the big queue) and having two windows can be confusing for the youngsters.

So a bit a experimentation revealed a better, simpler command line solution.

  1. Connect the second display
  2. Open a Terminal Window 
  3. Type xrandr --auto


This should automatically detect the new output device and set-up mirroring.

Some other useful commands

xrandr --listmonitors 


(this lists all the detected monitors)

xrandr --output <laptop monitor name> --same-as <projector name> 

(this forces mirroring - you can also add in other parameters, for example if the aspect ratios of the two screens were very different).








Tuesday, 21 August 2018

Bash wifi network switcher script for Raspberry Pi

I had a situation where I had a Raspberry Pi 3B+ in a location where there were two usable wifi networks in range, but neither were particularly reliable in terms of Internet access. The wifi networks themselves would stay up, but the ADSL connections used by the  routers would sometimes drop and stay down for a while (in the case of one, until someone rebooted it).

So I wanted the Pi to switch from one network to the other in the event of losing Internet connectivity.

So I wrote a bash script that can be run periodically by cron.


There are a number of ways to achieve this,  including using additional packages like nmcli, but I wanted something that should just work on a plain version of Raspbian.

I also decided to test it on older Pis without built-in wifi and using a doingle instead. I found that a few tweaks were required to get the script to work reliably. 

I also encountered one situation where the Pi under test ended up not connected to any wifi network at all. Annoyingly I have not been able to reproduce that outcome to identify what went wrong.

The script is set to switch between two networks, SSID1 and SSID1 - obviously you'll need to change these names to reflect your own environment. 

To use the script you'll need two different copies of your wpa_supplicant file - which contains the network name and pre-shared key (password) required to authenticate - , one for each SSID.  Give them sensible names like  wpa_supplicant_1.conf and  wpa_supplicant_2.conf.

The script logs to a file wifi.log - this can be useful for debugging. It also echoes to the terminal too, to make it easier to see what's going on when testing. If you don't want any of this, just remove or comment out the 'echo' lines. 

There's no reason that this shouldn't work on other Debian distros or more widely on Linux, but I have not tested it.

The script needs to be run on a Pi with sudo. If you want to schedule using cron, then type 

sudo crontab -e

and then add a line to run as frequently as you like. For example:

0 */2 * * * /home/pi/wifitest.sh

Don't forget to make the file executable

chmod +x /home/pi/wifitest.sh

Tuesday, 14 August 2018

Testing Adafruit Feather M0 LoRa 900MHz in the Alps

One of my birthday presents this year was  two 900MHz Adafruit feather M0 LoRa 800MHz boards. I hadn't had a chance to try them out  but just before going on holiday I realised that our destination in the Alps might provide a nice testing ground (or mountain) so added them to my hold luggage.

I know that LoRa tech is capable of impressive line-of-sight distances when there are no obstructions, but as I hadn't had time to pack my HAB gear, I needed to find some other way of testing the range.

The Feather boards are a nice size and I was just using a length of wire as an antenna. Example client/server Arduino code from the Radiohead RFM0x library was good enough for my purposes. Each board would blink its LED when it received a packet so I could see if data was being exchanged.

For the tests, one board  stayed back at base in the chalet - shoved out the Velux window for maximum height.


It was very sunny and hot so I decided that the base Feather ought to have some shade.


The second board came along with me on my travels, powered by a battery pack.


Over a few days I took the Feather out with me, first of all just cycling around the town, then for a grander test, heading up the mountain in the Grand Massif tele-cabin.



On the ascent, I was surprised to not be picking up any packets, even though I had been able to get good reception if I wondered about in the car park at the bottom. Thinking that the cabin itself might be acting as a bit of a Faraday cage, I poked the Feather out the window, and immediately started seeing the blinkin' red LED.


The contours of the mountain meant that there was actually quite a lot of rock and trees in between the two boards right at the top of the tele-cabin, and despite some wandering around to try to get better reception, the LED stayed off until we'd trekked some way  further up the mountain.

Fortunately you can also get a chair lift even higher, so we continued  to ascend to 2100m (the chalet itself is at 700m).


At the top the signal was very strong and with binoculars we could actually see the chalet down in the valley.

I recorded the various locations using the GPS Waypoint app on my phone and then exported these via KML into Google Earth. Red markers are places where there was no reception, green are where packets could be received.



This allows me to calculate the straight line distance between the two boards - the maximum distance was 5.86km, 


Even on flat ground,  with trees and buildings in the way, I was still able to exchange packets at 2.60km, and after that point I rounded the edge of the opposite mountain which probably blocked any further data.



So I was very impressed with the boards. They'll certainly be up to relaying data from my new shed....



Thursday, 28 September 2017

Pivarium: care for your reptiles with a Raspberry Pi

It's been a while since there’s been a new addition to the family and I’d forgotten how much preparation is involved. All the familiar concerns that I remembered from when the boys were born came flooding back: you need to make sure the new arrival is not too hot or cold, provide a safe environment that they can’t escape from, ensuring they’re safe at night...

Snakes, I've discovered, are a lot like children. Except easier to feed. 





Anyway, faced with such challenges there is only one response: make some stuff to help.

Of course when the boys were born, the Maker community wasn’t as well established and, Raspberry Pi, the core of many IoT projects had yet to be born itself. So this project gave me an opportunity make up for it now.  The Pivarium deals with the the main requirements mentioned above.

Monitoring the environment inside the vivarium.


Snakes are ectotherms - they have no internal means of regulating metabolic function and maintaining homeostasis. In cold weather, snakes tend to be sluggish as their metabolisms slow down, whereas in warm weather they tend to eat more and move more quickly.  So in captivity they need to have a temperature gradient available so that they can move to a cooler place when they get too hot and vice versa. The Kernels vivarium has a  thermostatically controlled ceramic heat lamp at one end but I wanted to monitor the temperature under it,  as well as at the opposite end where there is more ventilation. 
I opted for DS18B20 temperature sensors because they are cheap and reasonably water -and hopefully snake pee - resistant. I was too lazy to convert the ends of the leads to female jumper sockets so I just used screw terminals and a small breadboard. My excuse is that this will make it easier to replace a faulty sensor in future. 
DS18B20 (left) next to probe from thermostat at 'hot end'

ADS18B20 at 'cool end'

The humidity in the Pivarium is also important, especially when the snake is shedding its skin so I wanted to monitor that as well I opted for a DHT22 which can also record temperature as well and is more accurate than the cheaper DHT11.  Therefore I placed it in the centre of the vivarium, attached to the roof. This gives me a third temperature reading to provide a good overall idea of what the gradient is like in the vivarium.
DHT22 mounted on roof

While I was testing and The Kernel was settling in,  I used a Pi Touchscreen to display a dynamic plot of the temperature and humidity values in real time. This was produced using Jupyter Notebook and the Python Matplotlib library. 




Once I was happy that everything was working and reasonably stable removed the touchscreen and swapped the Pi 2 for a Zero W. I still wanted to keep a graphical record of the environment though, so I created a data bucket on InitialState and upload regularly the data to produce a nice dashboard that I can check from anywhere that I can get on the InterWebs. 


InitialState dashboard


For a local display, I dont really need graphs - just the headline readings are fine. I also didnt want something bright and flashy like an LED matrix so I opted for the excellent Pimoroni InkyPhat. This is perfect as I only need to update the values every 5 minutes or so - things dont change that rapidly in the Pivarium.  Although the InkyPhat is limited to three colours, thats fine.  I want to easily see if a temperature is outside the desirable range for that area of the Vivarium, in which case the value is displayed in red text, otherwise black. I also display the time so I can tell that the readings are current and that the Pi or Inkyphat hasn’t stuck or crashed. 



I want to easily see if a temperature is outside the desirable range for that area of the Vivarium, in which case the value is displayed in red text, otherwise black. I also display the time so I can tell that the readings are current and that the Pi or Inkyphat hasn’t stuck or crashed. 

Night Vision

The next task was to see what The Kernel was getting up to at night. At a later stage I might put a camera in the vivarium itself, but for now I’m happy to have a second Pi outside with a Pi Noir camera and some IR LEDs, all mounted in a Lego frame.   Reflection from the vivarium glass in minimal and I can easily position the whole thing to focus on a particular area (e.g the hot or cold hide, the water bowl etc). I didnt want to record all the time so I used Motion software to detect when activity was occurring and start recording then. 

Ive been able to capture some good footage of The Kernels nocturnal behaviour. My favourite so far has been this clip of him having a big drink and then burping.



Houdini

The final task was to prevent The Kernel from unexpectedly leaving his lovely home. Corn snakes are renowned escape artists and will find a way out through any small crack or opening. A common escape route is cased by the sliding vivarium doors not being closed properly and the patient and surprisingly strong guest levering their way out when nobody is looking. A simple remedy is to always fit the sliding vivarium lock and mark its position on the bar so that you know the doors are fully closed. However it is really easy to forget this or to not lock the doors immediately and then forget to do it later (especially when removing snake poo). So  I wanted to add some blinkin LEDs to provide an immediate visual indication that doors were not secure. 
I found some nice chunky contact switches (with a satisfying click). These have 3 spade-connector terminals, a different pair of which are connected together when the switch is closed or open.    I designed some 3D printable brackets to fit hold them and allow easy fixing to the side of the vivarium. I also added a hole and channel for a blinking LED.
I also 3D printed some handles to fit onto the existing glass squares that are used to slide the doors. These press against and close the contact switches: the advantage of 3D printing these was that I could precisely adjust the size so that the switch is only fully depressed when the door is completely closed. 



As usual, the Python gpiozero  library makes the code to control these switches embarrassingly easy, especially using source/values.


from gpiozero import Button,LED
leftside = Button(20)
leftside_led = LED(21)
leftside_led.source = leftside.values
rightside = Button(19)
rightside_led = LED(26)
rightside_led.source = rightside.values

You can see the complete Python code for the Pivarium here. The STL files for the various 3D printed files and the Jupyter Notebook file used in testing are also there. 

Wednesday, 2 August 2017

Introducing your Pi-rsonal Trainer

Since starting a new job earlier in the year I've had to make a lot of  adjustments to my fitness schedule. One thing I really miss are the exercise classes I used to attend. I particularly miss the High Intensity Interval Training sessions which were a great way get a quick cardiovascular workout.

I'd been rolling my own version at home in the back garden for a few weeks and found that although these sessions worked reasonably well,  I missed the class instructor who used to call out the next exercises and provide motivational commentary. Keeping track of what exercise I've just done gets increasingly difficult the more tired I get.  I also found it annoying to have to check my watch for when to pause between exercises and re-setting a timer every 20 seconds is annoying.

Obviously it would be hard to simulate the enthusiasm of a trainer but the exercise choice and timings seemed like a straightforward thing to automate with a Raspberry Pi.


I wanted a visual and audible alerting mechanism and something that would be small enough to be readily portable and run from a standard power bank.

Here is the finished prototype: my Pi-rsonal Trainer.


BoM

Pi Zero running Raspbian Jessie-lite and with the ScrollPhat HD Python library installed.
Pimoroni ScrollPhat HD
Pimoroni Pico HAT Hacker
Buzzer
Two push buttons

Construction



1) Solder a standard male header onto the Pi Zero.
2) Solder on the Pico HAT Hacker, being careful not to let the solder wick too far up the pins.
3) Solder a small buzzer directly on to the Pico HAT Hacker between the holes for Ground and GPIO 18
4) Solder two buttons onto the Pico HAT Hacker, one between Ground and GPIO 9 and the other between a different Ground pin and GPIO 19.
5) Solder a female header on to the ScrollPhat HD and then mount this onto the Pi.


Operation

For my HIIT sessions I like to have 4 repetitions of 10 x 20s periods of exercise interspersed with 10 second rests.

Some simple Python code runs at startup-up. When the bigger button (on GPIO19) is pressed, the sequence begins with an on/off flash of all the LEDs on the ScrollPhat . An exercise is selected at random from a list and this choice is scrolled across the matrix for 5 seconds, followed by a 5 second countdown accompanied by beeps. Then there's another flash and the 20 second exercise period begins. The exercise being undertaken is constantly scrolled across the LED matrix until the last 5 seconds when there's another beeping countdown. Then there's a 10 second rest period during with the next exercise is scrolled. And repeat 10 times.

Then a 30 second break.

Then repeat all that 4 times!


The LEDs of the ScrollPhat HD are nice and bright, and visible in full sunshine. The beeps are annoyingly shrill so that I can hear them even though I'll normally be listening to music on my earbuds. This means I don't have to keep watching the LED display to now when the various intervals are finished.

The code is easily customisable if you want different exercises or want to alter the timings. You could just as easily program a Yoga session rather than a HIIT workout!

Thursday, 9 February 2017

MakeTronix Alarm and GPIOZero on Raspberry Pi

I funded the MakeTronix Alarm on IndieGoGo because it contains many of the components I usd with Raspberry Pi at CoderDojo, but in one compact package. Don't get me wrong, I'm all in favour of having learners build the circuit using a breadboard, but sometimes there just isn't the time to do that and code it.

The board arrived very quickly and it is a nice, neat package. I was pleased that they kept the board to 26 pins as this will enable it to work with my trusty set of original mode Bs.

The online documentation is easy to find but I have to say I found it a little disappointing. It seems weird to not show a picture of the board mounted on a Pi in the “connecting the board” section. The written description is entirely accurate but a simple diagram would be much better, especially for younger users. I was also surprised to find that the code examples downloaded from the MakeTronix github don't use gpiozero. There's nothing wrong with using the Rpi.GPIO library – it works perfectly – but I believe  gpiozero is much better for those who are new to Python and this board is being marketed as a “fantastic educational circuit board for learning programming”. They've tried to abstract out the key functions into a library file that the other examples import, but this feels a bit unwieldy, again especially for novice Pythonistas.

I also couldn't get the full alarm code to work. It turned out this was nothing to do with the code: the PIR that shipped with my kit didn't work correctly and would not trigger on motion at any sensitivity. Luckily I have plenty of these PIRs and substituting in a replacement got everything working.

Nevertheless I decided to write a gpiozero version. It uses a couple of lambda functions which you might argue are too opaque for beginners (and I'd probably agree) but they do remove the need to give each button its own when_pressed function individually.

Here's why I love gpiozero – all sorts of hardware control is possible with simple, easy to understand syntax. My MTAlarm code does the following:

1. Activates the PIR and waits for motion to be detected. The LED glows/pulses to indicate that the alarm is active.

2. When motion is detected, the LED starts flashing.


3. If within 10 seconds  the correct code is entered (each key beeps when pressed and DEL acts as backspace) the alarm is disabled.






If not, the buzzer starts to beeeeeep constantly.



Friday, 23 December 2016

Amazon Alexa controlling Raspberry Pi GPIOZero Xmas lights

I've been looking for a home IoT project to setup with Amazon Alexa and my Raspberry Pi powered Christmas Tree seemed like an obvious choice.




Here's how it works:

There are 5 sets of cheapo xmas LEDs connected directly to GPIO pins on the Pi. I then use Python and GPIOZero to turn them on and off, do a bit of PWM and run some fancy sequences.  I've then integrated this code into a simple Python Flask app that essentially provides a web-interface to activate the LEDs.

The Pi is also running this awesome Home Automation Bridge code  from BWS Systems. This emulates the Philips Hue light system and can be easily configured to send web requests to other devices, in this case my Flask app.

Finally, Alexa discovers the HAB and merrily passes requests to it based on your voice commands.

All this runs fine on an old 512MB Raspberry Pi model B.

Step-by-step

1) Get and SD card with the latest version of Raspbian. Boot it and connect to your wifi

2) Find the if address of your Pi


pi@raspberrypi:~ $ ifconfig wlan0
wlan0     Link encap:Ethernet  HWaddr 00:c1:41:39:0c:3e  
          inet addr:192.168.49.213  Bcast:192.168.49.255  Mask:255.255.255.0
          inet6 addr: fe80::1185:ec1e:49f9:d936/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:2270 errors:0 dropped:2 overruns:0 frame:0
          TX packets:646 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:327701 (320.0 KiB)  TX bytes:94619 (92.4 KiB)

3) Download the jar file for the HAB:


wget https://github.com/bwssytems/ha-bridge/releases/download/v3.5.1/ha-bridge-3.5.1.jar

4) Run this jar file:


sudo java -jar -Dconfig.file=/home/pi/habridge/data/habridge.config /home/pi/habridge/ha-bridge-3.5.1.jar

5) Point a browser at the IP of your Pi (from step 2). You should be able to connect to the HAB - click on the Bridge Control tab and you should see a screen like this:


 6) Clone my github with the  Flask app. There are two versions of the code available: one is setup to use 5 sets of LEDs while the other is a cut down version with just a single LED string configured, connected to GPIO 14 and ground. I'm assuming you've just got one LED (or a string of LEDs) from now on. 

7)  Run the app:

pi@raspberrypi:~/gp0web $ python singleLED.py 
 * Running on http://0.0.0.0:5000/
 * Restarting with reloader

8) Now we can configure our HAB. Click on the 'Manual Add' tab and fill-in the fields as shown below. The 'Unique ID' field will self-populate once you save your settings so don't worry about that.



Don't forget to change the IP address based on your setup.

9) Now save the settings and then test them. Click on the Bridge Devices tab and try to turn your LEDs on/off using the Test buttons.

If you encounter problems, check you've typed the URLs correctly and see if the Flak app is showing any errors.

10) If all is working, the final configuration  step is to ask Alexa to 'discover devices'. It should respond that it found one (unless you already have other devices on your network).

11) Now you should be able to ask Alexa to "turn on tree" (or whatever name you gave to your device in step 8).