Skip navigation

Raspberry Pi Projects

4 Posts authored by: biglesp

16992757006_de6faf7402_o_d.jpg


The Raspberry Pi camera is an awesome piece of kit and can really liven up your next project. But how can you get started with it? Well let’s grab a camera, Pi 2 and a few cheap components and build three projects based on the camera.


17017297212_127fb3e02e_o_d.jpg


Setup


Installing the camera is quick and easy and to start the installation firstly you will need to locate the black connector marked CAMERA between the HDMI and Ethernet ports.

Carefully lift the top and bottom edges of the connector vertically, they will gently slide up and then stop when in place. Be careful as the CAMERA connector is rather fragile, you will only need to use a little pressure on the connector.

Remove your camera from the box and slide the ribbon connector into the CAMERA connector, ensure that the blue edge faces the ethernet port. Be careful handling the camera it is rather fragile and sensitive to static. With the ribbon inside the connector gently push the connector edges back down, locking the ribbon in place.


16992755516_409baca2ea_o_d.jpg

 

With the camera in place, boot up your Raspberry Pi and from the desktop open LXTerminal and type the following

 

 

At the menu navigate to Enable Camera and press enter. In the next screen select Enable, and then navigate to Finish, which will prompt you to reboot your Raspberry Pi. Do this and allow the Pi to reboot, thus enabling your camera.

With the camera enabled we next need to check that it has been configured correctly and to do that we use the command raspistill in  LXTerminal.

 

 

This will launch the camera and show a preview on the screen for a few seconds, compose yourself and it will take the picture. You can then open the picture via the file manager. It should be in /home/pi or in the directory where you used the command. If this does not work, check that you have connected the camera correctly and that raspi-config shows the camera as enabled. Remember do not remove the camera from the connector while the Raspberry is on, it will cause damage to the camera.


For the last setup step we shall install the Python PiCamera libraries so that we can hack the camera using Python.


In LXTerminal issue the following command

 

 

Once this is complete in LXTerminal type



Project 1 - Take a picture with Python


Our first project is rather simple but it shows how to use the PiCamera library and gives us a quick introduction to the library.


What will you need?

Raspberry Pi 2Raspberry Pi 2

Raspberry Pi CameraRaspberry Pi Camera


 

At this time the application has opened the shell, where we can issue commands / test logic on a line by line basis. We really need to be in the editor, so click on File and New Window to launch an editor window.

As soon as the editor window is open, click on File and Save and name the file, anything BUT camera.py This is a good practice to get into as it means that any subsequent saves are handled quickly.

So we start our code by importing two Python libraries.


Time - To control the speed of our project

PiCamera - To use the camera with Python

 

 


So with the libraries in place we now turn our attention to creating the main body of code. We start by using



To rename the picamera library into something more manageable, in this case “camera”.



Then we create a preview of the image, in the same way that your mobile phone shows a preview of the scene before the image is taken. This preview stays on screen for 5 seconds before capturing the image to the Desktop, and lastly the preview window is closed, ending the project.


When ready, save the code as project1.py and then click on Run >> Run Module.

The code will start a preview of the picture to be taken, wait 5 seconds so you can compose yourself and then take the picture saving it to the desktop. Then the preview will end.

When the camera is active, you will see the red light illuminate in the corner of the board.


So how did your picture come out? Was it upside down? Too dark or light?

Well PiCamera has a few features that can be tweaked.


Rotation - You can easily rotate an image in 90 degree segments by using

camera.rotation = 180

This will flip the image upside down.


Saturation - Add more or less color to your picture, values can be between -100 and 100

camera.saturation = 50


Brightness - Tweak your image if it is too dark or bright. Values are between 0 and 100

camera.brightness = 50


Resolution - Create images at different resolutions. Values are entered by width and height, so an image 1920x1080 is 1920, 1080


There are loads of tweaks that you can make and for the full list head over to Dave Jones’ great resource http://picamera.readthedocs.org/en/latest/index.html

 

Project 2 - Take a picture using a button


What will you need?

Raspberry Pi 2Raspberry Pi 2

Raspberry Pi CameraRaspberry Pi Camera

Push Button / SwitchPush Button / Switch

BreadboardBreadboard

Male to Female Jumper Wire x 2

 

Before continuing please ensure that you have followed the above setup instructions.


Taking a picture at the touch of a button is something that we take for granted thanks to mobile phone technology and cheap consumer electronics. But in this project we will deconstruct the process and create our own push button camera using a few common electronic components.

We start this project by attaching the hardware to the Raspberry Pi.

 

Project2_bb.png

 

With the hardware attached our focus shifts to the code, more specifically the Python code that will power this project.

To start open LXTerminal and type in the following, remember to press enter at the end of the line.

 

 

This will open the Python 3 editor, commonly referred to as IDLE. At this time the application has opened the shell, where we can issue commands / test logic on a line by line basis. We really need to be in the editor, so click on File and New Window to launch an editor window.

As soon as the editor window is open, click on File and Save and name the file, anything BUT camera.py This is a good practice to get into as it means that any subsequent saves are handled quickly.

So we start our code by importing three Python libraries.


Time - To control the speed of our project

PiCamera - To use the camera with Python

RPi.GPIO - To use the GPIO pins with Python

 

 

With the libraries added, save your work before progressing.

Next we setup the GPIO, firstly we configure the pins to use the Broadcom pin mapping (see diagram) which is not a logical layout, rather it breaks out the pin numbering from the Broadcom System on a Chip (SoC) that powers the Pi.

 

 

We use a variable to store the pin number on to which our push button is connected.



Then we setup the button to be an input and to be set high, in other words turned on at the start of the project.



We now create an infinite loop to constantly look for the button to pressed and when that happens the camera code is launched.



Now we make a few configuration changes to the camera settings, firstly changing the resolution, and then the saturation and brightness.



Now we have the button detection code, this will look for a change to the GPIO pin attached to the button and when the pin goes from high to low the preview screen will come to life, wait for 5 seconds and then capture your photo before closing the preview and waiting for another button press.



With the code complete, save it as project2.py and then go to Run >> Run Module. Wait a few seconds and then press the button to trigger the camera to life. Project 2 is complete.


Project 3 - Take a picture using Minecraft


16747589098_dd81522fc8_z_d.jpg


What will you need?

Raspberry Pi 2Raspberry Pi 2

Raspberry Pi CameraRaspberry Pi Camera


Minecraft is not only a great game, it is also a great source of Pi projects, and here is a camera triggered in Minecraft that you can code in less than 30 minutes.


For this project you will need to close any Python 3 windows that you may have open. Currently the Minecraft Pi API only works with Python 2.

Then open LXTerminal and type the following.



Then click on File >> New Window to open a new editor window.


We start as ever with importing the libraries that make this project possible.


Time - To control the speed of our project

PiCamera - To use the camera with Python

Mcpi - To link Python with Minecraft



Next we create a link between our Python code and Minecraft. We create a variable called “mc” and that stores “minecraft.Minecraft.create()”, so whenever we use “mc” it tells Python to replace it with the long string of text.



So we now reach the main body of our code, this is the loop that will constantly check our position in the Minecraft world. So we start with the loop, a simple infinite loop called “while True” and we then create a variable called pos and store the player's current position in the world.



Now we create a conditional statement, that will check our current position and compare it to the a hard coded value, in this case checking that our location on the X axis  is -7.0 and when this is true a message is posted to the chat window before reusing the Python code that we wrote earlier to take a picture.



Save your code as project3.py but do not run it yet. Navigate to the Raspbian menu and go to Games and select Minecraft Pi.


16315205993_49ebc826f2_o_d.png


After a few seconds Minecraft Pi will be on screen, go ahead and create a new game and then a new world. When the game starts you will be dropped near to the X Y Z coordinates 0,0,0. To move around use the W A S D keys, and to look use your mouse. Spacebar is used to jump. Get a feel for the controls and then head to -7.0, you can see your location as a co-ordinate in the top left of the window.

Once there, open the inventory by pressing E on your keyboard, then find the signpost tool and left click on it to use it. In the game world, drop a sign post to show where -7.0 is.


16810526967_5e6f85c6e9_o_d.png


With that done, press TAB on your keyboard to release the mouse from Minecraft and navigate back to our Python code. Click on Run >> Run Module to start the project. Navigate back to Minecraft, the easiest way is to click on the window to bring it into focus.

Now move to -7.0 again and the camera should spring into life!


So there we have it. Three projects all using the PiCamera in a different way. What can you do with the PiCamera and the Raspberry Pi 2?


All of the code for these projects can be found at https://github.com/lesp/Element14_PiCamera


Recently we built a Plex Media Server using the Raspberry Pi 2, at the time the Raspberry Pi 2 was the most powerful board in the Raspberry Pi range. But on February 29th 2016 the Raspberry Pi Foundation announced their latest board, the Raspberry Pi 3.

 

IMG_4105.jpg

Photo Credit - Raspberry Pi Foundation

Technical Specifications

  • Broadcom Quad Core 64bit CPU 1.2GHz  (BCM2837 SoC)
  • Broadcom BCM43438 WIFI and Bluetooth connectivity
  • 1GB RAM
  • VideoCore IV GPU and 3D now clocked at 400MHz and 300MHz respectively.

 

Raspberry Pi 3 Improvements

 

The new Raspberry Pi 3 is now 66% faster than the Raspberry Pi 2 and is approximately 10X faster than the original Raspberry Pi. The CPU of the Raspberry Pi 3 is an ARM Cortex A53 clocked at 1.2GHz per core, giving us the most powerful Raspberry Pi ever!

So how can this help our media server project?

 

  • Faster CPU, more CPU power enables our Raspberry Pi 3 to index our media library quicker.
  • 64bit CPU, 32bit operating system. The new Pi 3 CPU is 64bit, and while the Raspbian operating system is still 32bit, the extra headroom is still utilised giving us a speed boost.
  • Scaling CPU. The new Raspberry Pi 3 CPU can scale, enabling it to power down when not in use but spring into life when needed.
  • WIFI. The built in WIFI of the Raspberry Pi 3 is really fast. Working to 'n' standard, we can send HD video from our Pi 3 to any device on the network...wirelessly!

 

So here is our guide to building a Plex media server using the Raspberry Pi 3.

 

For this project you will need

 

  • A Raspberry Pi 3Raspberry Pi 3
  • A laptop running Windows/Mac or Linux
  • A minimum of 8GB SD card (Class 10 for best results)
  • A minimum of a 2A power supply but for best results use a 2.5A power supply2.5A power supply
  • An Ethernet cable connected to a router.
  • An external USB hard drive, preferably powered by an external power supply.

 

We start the project by installing the latest version of Raspbian on to an 8GB or greater SD card. It is vitally important that we use the latest version of Raspbian with the Raspberry Pi 3 as it has tweaks that enable the Pi 3 to really fly. The best tutorial on how to install Raspbian on an SD is provided by the Raspberry Pi Foundation and can be found on their blog

With Raspbian installed we now need to boot our Raspberry Pi. Insert the microSD into the Raspberry Pi, then attach any peripherals such as keyboard, mouse, HDMI, Ethernet to the Pi. Lastly attach the power cable to boot the Pi.

When your Pi has booted to the desktop, click on the menu to the top left of the screen and go to the Preferences menu. From there select the Raspberry Pi Configuration application.

In this application we need to change the boot behaviour so that the Pi boots to the terminal and is logged in. We’ll also change the memory for the GPU to only use 8MB of RAM

With these changes made, save and exit the application. You will be asked to reboot, do so before progressing.

With our Pi rebooted we now find ourselves at the terminal. It may seem a little scary at first but the terminal is the best way to work with a Linux computer.

 

Setup our software

Our next goal is to install the software necessary for our Pi.

First we update our list of available software and then upgrade the software. We will use an operator to join two commands together. The first command updates the list of software and if that completes successfully, then the last part of the sequence, a software upgrade is started and any suggested files are auto installed.

In the terminal type.

 

sudo apt-get update && sudo apt-get upgrade -y

 

Now we are going to upgrade the distribution, Raspbian, software. To ensure that our operating system is fully up to date. In the terminal type.

 

sudo apt-get update && sudo apt-get dist-upgrade

 

Once completed and the terminal is returned to you enter the next command to install the HTTPS transport package to enable access to HTTPS content over the Internet.

 

sudo apt-get install apt-transport-https -y --force-yes

 

Next we shall download a key that will authenticate our downloads to ensure they are safe

 

wget -O - https://dev2day.de/pms/dev2day-pms.gpg.key  | sudo apt-key add -

 

With the key downloaded we now add a new repository to our list, this repository is provided by dev2day.de who has worked on the packages that will power our Plex install.

In the terminal type

 

echo "deb https://dev2day.de/pms/ jessie main" | sudo tee /etc/apt/sources.list.d/pms.list

 

We now update our list again, to ensure that we now have the latest updates for the Plex Media Server.

 

sudo apt-get update

 

Lastly we install the Plex Media Server software.

 

sudo apt-get install -t jessie plexmediaserver -y

 

The install will only take a few minutes and once completed the Plex Media Server will automatically start as a background service on your Pi.

At this point it is worth rebooting your Raspberry Pi 3 as proceeding without a reboot caused a bug when trying to configure the Plex server via the browser.

To reboot in the terminal type.

 

sudo reboot

Networking

With the Raspberry Pi 3 we saw the introduction of built in WIFI! Yes we no longer need USB dongles to connect. The WIFI chip on the Pi 3 is a BCM43438 which is rated up to Wireless N which gives us plenty of bandwidth to stream video over WIFI.

Connect to WIFI (Optional step, can be skipped if using Ethernet)

 

Connecting to WIFI from the terminal is rather easy, but looks rather scary!

 

Firstly we need to find out the name of our router, the SSID.

In a terminal type

 

sudo iwlist wlan0 scan

Look for the name of your router. It should look something like this, replace MY_ROUTER with the name of your router.

 

ESSID:"MY_ROUTER"

 

Next look through the text for your router and see if you can spot a line similar to this.

 

IE: IEEE 802.11i/WPA2 Version 1

So now we need to add our network details to a file called wpa-supplicant, in the terminal type.

 

sudo nano /etc/wpa_supplicant/wpa_supplicant.conf

 

In the text editor, navigate to the bottom of the text and add the following. Obviously change the ssid and psk to match the name of your router and the password you use to get online.

 

network={
  ssid="MY_ROUTER"
  psk="THE PASSWORD YOUUSE TO CONNECT TO THE ROUTER"
}

 

Save your work by pressing CTRL + O then press Enter. Next Press CTRL + X to exit the editor.

 

The changes should be automatic, but it is prudent to make sure by typing the next two lines one after another.

 

sudo ifdown wlan0
sudo ifup wlan0

 

You can check your IP address by typing

 

ifconfig wlan0

 

Your IP address should pop up for the interface wlan0, which is our WIFI card.

The best test to check that this works is to reboot your Raspberry Pi and see if it auto connects to the WIFI. To reboot type.

 

sudo reboot

 

Fix IP address of the Pi

 

To ensure that we can discover our Pi on a network we will now fix the IP address of the Pi.

First we need to find out the IP address, in the terminal type.

 

hostname -I

 

Write down your IP address!

Now let's fix the IP address, in the terminal type

 

sudo nano /boot/cmdline.txt

 

At the very end of the line we will add the IP address that we earlier wrote down. So type

 

ip=THE IP ADDRESS YOU WROTE DOWN

 

With the IP entered press CTRL + O, then Enter to save your changes.

Now press CTRL + X to close the file.

Now reboot your Pi to make the changes permanent.

 

sudo reboot

 

With your Pi rebooted we shall now test that we can access the Plex server. On your laptop or desktop PC open a web browser and type your IP address followed by :32400/web so for example I typed.

 

192.168.0.90:32400/web

 

24841031413_78331093d4_b_d.jpg

 

This will now open the Plex Media Server software and we will need to read and accept the Terms and Conditions before progressing.

Once Plex has loaded take a few moments to get familiar with the interface. Specifically the libraries, which will house your media collection.

The SD card of our Raspberry Pi is rather small, so let's add an external hard drive and store our media there.

Plug in your USB drive. Nothing will happen in Plex until we mount the drive. In Linux, mounting a drive means that it is ready to be used. On your Raspberry Pi, in the terminal type

 

dmesg

 

You will see a lot of text whizz up the screen but keep a look out for your hard drive.

So now lets create somewhere to link our hard drive to the Raspberry Pi this will be a directory called “library”. In the terminal type

 

sudo mkdir /mnt/library

 

Now we shall open a text editor and add a line of code to mount the drive on boot. For our drive we used a FAT32 formatted drive. As this is the only USB drive it will be given the assignment “sda” and if the drive has one partition, where our data is stored, then it will be “1”. This gives us the location of our media which is “sda1”.

 

sudo nano /etc/fstab

 

25467761615_c0b2d45027_b_d.jpg

 

So now we shall mount our drive, got to the last line which starts with a “/” and make a new line under it. Enter the following and try and keep your spacing similar to those above.

 

/dev/sda1    /mnt/library   vfat   defaults    0    0

 

To save your work press CTRL + O followed by Enter. Then to exit press CTRL + X.

Reboot your Raspberry Pi.

 

sudo reboot

 

Once the Pi has booted back up navigate to your content by typing.

 

cd /mnt/library

 

Now we need to see where our content is, so to find it type

 

ls

 

You should see lots of directories and files, just as you arranged them on your main computer.

Our next step involves enabling access to the files for any user. As our server will be in our home we shall enable access to all of the content for all of the users. Typically this is not the done thing for big servers in production but for our server this is fine. So to enable access we need to type

 

sudo chmod 777 -R /mnt/library

25349753862_c979d92f73_h_d.jpg

On a Raspberry Pi 2 this took a few minutes to complete, but thanks to the Pi 3 and its new processor this time is greatly reduced. But the time will vary depending on the amount of files in your library.

So now that we our drive ready to serve our media, let's start using it!

Back to our laptop/PC and open your web browser to your Plex Media Server.

You will be prompted to add a library, so go ahead and do so. Now which library you add depends on what you have. I chose to add a couple of TV series. When ready click on “Add Library” to import the media.

 

24837201614_aacabb5271_b_d.jpg

24841031493_351b6b9f21_b_d.jpg

 

Depending on the amount of media that you have to import this process may take minutes or hours, so please be patient and wait for the process to finish. One thing we can confirm is that the Raspberry Pi 3 indexed our library in a significantly quicker time than the Pi 2.

When the media is imported, Plex will try its best to grab the metadata, the information about the content such as genre, IMDB data, actor details etc.

 

25702274085_7eaa6d6549_o_d.png

24841032293_264f6a1578_o_d.png

 

Music for all

25702273695_9ce678920f_o_d.png

Importing a directory full of music is also made easy, it is just another library of content to Plex. Importing is handled in the same manner as video media, Plex will also search for the artists, albums and genres of your music, providing information on the album and artists thanks to meta data.

 

25583574972_3e0fe43a02_o_d.png25401441110_05b4613bb3_o_d.png

 

 

Multi User Access & Chromecast

 

25075947343_1741bb27bb_o_d.png

Plex streaming to a Windows tablet

 

The huge benefit of Plex is that any user on the home network can access any of the media in the library. So children can watch their favourite films on the mobile device, parents can listen to music or podcasts or share their family photos on their laptops.

 

Plex can also be streamed to a chromecast device, enabling high definition movies to be enjoyed on the big screen.

Listen to all of your music across your entire home and all you need is a Raspberry Pi and a little Linux know how

With Christmas almost upon us it’s time for our annual Element 14 Christmas Project. Last year we built a Santa Trap that used a Raspberry Pi and camera to photograph Santa as he delivers presents around the globe.

For 2015 we are going to create an IoT (Internet of Things) Christmas tree that will accept commands via Twitter, so we can control our tree from afar.

 

 

For this project you will need

A Raspberry Pi A+ or B+, this project does not work with Pi 2.A Raspberry Pi A+ or B+, this project does not work with Pi 2.

The latest version of Raspbian

A breadboard

A selection of Jumper cables (Male to female, male to male)

SN74AHCT125 Level converterSN74AHCT125 Level converter

2.1mm female barrel jack adapter

Terminal blockTerminal block

5v 4A power supply

A Neopixel string

All of the code for this project can be found in a Github repository

Raspberry Pi Zero Update

This project is compatible with the new Raspberry Pi ZeroRaspberry Pi Zero, enabling a truly low cost alternative that can be easily embedded.

23295082496_d5cb5fb294_k_d.jpg


Hardware Setup

Firstly we need to build the circuit for our Raspberry Pi. Firstly we shall connect our 74AHCT125 to a breadboard. Ensure that the pins are spread over the central channel of the board. You may also need to bend the pins so that they fit into the board, this can be done by gently pressing the chip against a solid surface.

Now we move to wiring up the chip and for this please refer to the diagram for more information.

IoTree_bb.png

Attaching the female barrel jack adapter to our power supply we now have two screw terminals, marked + and -. Unscrew each terminal and attach a length of wire or a male to male jumper cable. Insert the + wire into the + rail of your breadboard, likewise with the - wire. You will also have a spare black wire for your neopixel strip. This is a GND that will also need to be attached to your - rail. Attaching a wire from any of your Raspberry Pi ground pins to the - rail will complete all of the ground connections.

For now do not apply power to your neopixels and double check all of the connections made before progressing.

Software Setup

Power up your Raspberry Pi and boot to the Raspbian desktop. Firstly we will need to download and install a few extra software packages and for this you will need an Internet connection before you proceed.

To update and install the software open a terminal and type the following, then press Enter.


With that complete we shall now download the rpi_ws281x Python library. In a terminal type


Then navigate to the downloaded directory by typing



Next we shall compile the software library by typing.


We can now change directory into a new directory called “python” by typing


Our final install step for the ws281x library is to setup and install the Python library. Type the following.


Installation complete!


Hardware Test

Before we get into the project we need to check that our hardware is working. Ensure that all of the connection to the 74AHCT125 chip, Raspberry Pi and the power supply are correct before applying power to the neopixels. Power up your neopixel power supply, nothing will happen until we run a test. In the Raspberry Pi terminal navigate to the examples directory inside the Python directory.

Inside the directory is a file called “strandtest.py” and we will need to edit it before testing. Type the following to edit.



In the nano text editor you will see a line that reads


Change this to reflect the number of neopixels that you have, we have 120 in our 2 metre string. Looking further down the text we can see


This means that every neopixel will be at full brightness and will draw a significant amount of current, so let's reduce that to 1/8th of the power by changing it.

Save your changes by pressing CTRL + O, press Enter,and then exit by pressing CTRL + X

With the changes made type the following to test your neopixels.

23182931465_f47643be6f_o_d.jpg

Right now you should be dazzled by an area of colors and animations across the neopixels. When you are happy that everything is working, press CTRL + C to stop the code.

Our last task before continuing is to install the tweepy library for Python. Tweepy is a library that enables Python to use the Twitter API. To install open a terminal and type.



Our next step is to create a Twitter app which will enable our project to communicate with Twitter. To do this go to https://apps.twitter.com/ and sign in.

Once signed in you will see a “Create New App” button in the top right. Click on it and you will see the application screen.

twitter-app.png

Fill in the name of your application and a description. You can use an URL for the website, but if you have a site, put it in there. You can leave the callback URL blank. Lastly you will need to agree to the terms and conditions before continuing.

Twitter_app_setup.png

You will now see a screen, displaying your app, all we are need from this screen is our API keys, which are secret so don’t share them out. Click on “manage keys and access tokens” and you will be taken to a new screen.

ConsumerKey_Secret.png

You can already see your API Key and API Secret but we also need an access token. Scroll down the page and you will see the relevant section. Click on “Create my access token”. The page will update to show your access token, again keep this information secret.

Access_token_click_on_me.png

Make a note of your API keys and Access tokens as we will need them later.


Our project

So now we can get down to hacking our IoTree (groan) into life. For this project you can use any text editor you wish but we shall be using IDLE for Python 2, which with the latest release of Raspbian Jessie, can now access the GPIO pins directly without sudo access.

As always we start by importing the libraries that will enable our project.



The main libraries are tweepy for our Twitter API, neopixel for our neopixels and time which is used to control the pace of the project.

Next we create a series of variables to store the API keys and Access Tokens that we created earlier.

 

We now reuse some of the code from the strandtest.py file that we tested earlier. Again we change the configuration to match the number of LED in our neopixel strip and set the brightness so that we do not exceed the max current available from our power supply.

 

We are also reusing the color wipe function from the strandtest.py example to produce a incremental change, pixel by pixel along the strip.


Next we create a class to listen to the stream of tweets on Twitter and act accordingly.


We create an if..elif..elif conditional statement that will check to see if one of three conditions is true. These conditions are the text “#E14XmasProject” followed by a color. If this is present then the color will be passed to the colorwipe() function we created earlier. So if we see “#E14XmasProject red” the colorWipe() function is told to use 255,0,0, which is red in the RGB color standards.

Next we create a function to capture any error messages and display them in the Python shell.


For our penultimate section of code we login to Twitter using our API key and Access Tokens before setting up our neopixels ready for use via the strip.begin() function.


Our last section of code is used to search Twitter for our hashtag “#E14XmasProject” and this will trigger the neopixels to change color. Of course you may wish to change your hashtag to something more personal, as if we all have the same hashtag then everyone’s IoTree will be changed at once…globally!


So with the code complete, save your project and click on Run >> Run Module to start. Nothing will happen until you send a tweet with your hashtag and color. So using your cell phone, tablet or computer send a tweet and your neopixels should turn on and change to the color your specified.


So there we have it, we have created our first IoTree device.

22554432444_accb582342_k_d.jpg

Happy Holidays


Many thanks to James Mitchell for his input relating to the Tweepy stream listener




The Raspberry Pi Model B+Raspberry Pi Model B+ has been with us for a few months now and there are a growing number of projects that make use of the extra GPIO pins.

 

B%2BLES.jpg

 

For this project we will look back to our childhood and bring a much loved game from our past into the future. The humble board game.

Board games have been a traditional family pastime for many generations but with the rise of computer games their novelty has started to dwindle. These card and paper based games have little to offer the children of today who have been brought up on a diet of downloadable content packs and gamer scores.

 

But what if we could take a game from yesteryear and adapt it using the Raspberry Pi?

 

15039632047_fe71e45672_z_d.jpg

Meet the latest interactive board game...Pythons and Resistors

 

This project is split into three parts

 

  • Assembling the board game
  • Assembling and testing the electronic components
  • Writing and testing the Python code

 

To build this project you will need the following equipment.

 

 

Game Rules

The board game is based on a simple snakes and ladders setup, with 100 squares in total via a grid of 10 x 10 squares. The object of the game is for 2 or more players to roll a dice and move their game piece to match the number given on the dice. If the player lands on a python's head, then they will slither down the game board to the tail of the Python. If the player lands on the bottom of a resistor then they will climb up the game board. The winner is the first player to reach square 100, which is at the top left of the board.

 

Board game assembly

The board game components consists of

 

  • The game board, printed on glossy photo paper
  • Sugru rubber game pieces
  • Neodymium magnets to trigger the reed switches
  • Spare components to decorate the game pieces.

 

board.png

 

Start by printing at least two copies of the game board as it is easy to make a mistake when assembling the game. While they are drying open a pack or two of Sugru. Sugru is a form of air curing rubber that starts life as a sticky ball with a similar consistency to blutack. Form the Sugru into the shape that you wish. When you are happy with the shape add about three neodymium magnets to the base of the piece ensuring that they are gripped firmly by the sugru. Also if you wish decorate the game pieces with spare components such as LED or resistors.

 

tT_2xSJDK4DX05QMNMF2lKi3Yv3JSx91_MVet2Xknxs=w900-h600-no

 

Assemble and test the hardware

With the game board and player pieces completed our focus turn to the wiring and components that are under the board.

 

Reed switch

At the head of every python and the base of every resistor we are going to place a reed switch on the underside of the game board. These reed switches will be triggered by the magnets inside of our game pieces. A reed switch is a tiny switch contained inside of a glass vial. The contacts that form the switch mechanism come normally open so a current does not flow through the switch. By placing a magnet near to the switch we can trigger the contacts to quickly make contact, with a small audible click / pop being heard when this is the case. When contact is made the current will flow through the switch and in this case the current will flow to a GPIO pin on the Raspberry Pi which has been configured to be an input and react when this happens.

The best place to start is by fixing the reed switches into place on the underside of the board. To easily locate the correct spot I used a magnet on the printed side to trigger the reed switch on the underside. Once found I simply used cellotape over the glass vial of the switch to fix it into place. Repeat this action for all of the reed switches for all of the pythons and resistors.

 

15101706357_93e287a4a2_z_d.jpg

 

Jumper leads

With the switches in place we must now attach jumper cables to each end of the reed switch component. In one end of the switch we will supply 3v3 power from the Raspberry Pi 3v3 pin and the other will be connected to the corresponding pin. It doesn't matter which side that you choose, just make a note of which side you will be using as the 3v3 supply as we will go into more detail on the wiring for this later in the guide. For these connections use a female to female jumper lead and slide the connections over each end of the reed switch then use cellotape to secure them firmly in place. Do this for all of the reed switches.

 

15101499099_9d104c6bae_z_d.jpg

reed switch.png

 

Wiring the 3v3

The Raspberry Pi can supply 3 volts, commonly referred to as 3v3 from multiple pins on the GPIO but because for this project there are more switches than there are 3v3 pins on the Raspberry Pi we must break out the supply using a breadboard. A breadboard is a great prototyping tool that enables components and circuits to be tested before soldering. Typically a breadboard has two sets of two rails which are on the outer most reaches of the board. These rails are marked + and – and refer to a positive voltage, in this case our 3v3 supply from the Pi and a negative voltage which is commonly called Ground, often shortened to GND. Any connection made on a rail is available to all of the holes in the same rail as the supply. So a 3v3 supply from the Pi connected to the + rail will be available to all other holes in the + rail. For this project we need to connect the 3v3 supply from our Raspberry Pi to the + rail of our breadboard. 3V3 is supplied via pin 1 of the Raspberry Pi, which is the top left pin nearest the micro SD card slot. Connect pin 1 of your Raspberry Pi to the breadboard, and then using Male to Male jumper leads connect the reed switch 3v3 connections to the + rail of the breadboard.

 

reed_switches.png

 

Connecting the switches to their respective GPIO pins

In this project we have used a number of reed switches which are triggered by magnets and supplied 3v3 from the Raspberry Pi. When a magnet is placed over the reed switch, the switch will close and supply 3v3 from the Pi, through the switch and back to the Pi via another wire connected to the other side of the reed switch. On the Raspberry Pi we will configure the receiving pins for each reed switch attached to each Python and resistor square to wait for a signal, in this case the voltage change and when it receives it will trigger an audio file to play. To connect our switches to their corresponding GPIO pin, please refer to the table below.

 

Connecting our push button

With the reed switches complete, we now need to install the push button that controls the roll of our dice. Our push button is connected from the 3v rail of our breadboard and to the GPIO 13 pin, which is pin 33 using the logical numbering layout. The best way to ensure a good connection is to solder the wires directly to the push button. If you can't solder it is easy to learn but should be attempted with an experienced maker and with safety equipment present. There are many great videos on Youtube to help your learning including one from Carrie Anne at the Raspberry Pi Foundation

You can wind the wire around the terminals of the button for a temporary "no solder" test

 

pushbutton.png

 

15265233526_0b4f26e803_z_d.jpg

 

Pythons

 

Board Square  Broadcom GPIO Numbering
3824
4725
688
997

 

Resistors

 

Board SquareBroadcom GPIO Numbering
1314
3915
6718
7223

 

GPIO.png

Wiring up our dice

Rather than use a traditional dice, we will build our own dice using 6 LED connected to the Raspberry Pi GPIO. The LED will light up to signify the roll of our dice, so if I roll a 3 then 3 of the LED will light up. The Raspberry Pi outputs 3.3v per GPIO pin which flows to the LED and will light it up rather brightly, but just like Roy Batty from Blade Runner "The light that burns twice as bright, lasts half as long" so we need to drop the voltage down using a resistor. For this project I chose to use 82 ohm resistors which run in line from the GPIO pin to the LED, dropping the voltage before it reaches the LED.

 

dice.png

 

For each of the LED that make up our dice, we need to complete the above connection, using a breadboard.

 

dice_LED.png

To connect each of the dice LED, use the above diagram as a guide, your wiring may vary depending on your breadboard.

The pins for each of the dice LED are as follows.

 

DiceBroadcom GPIO Numbering

1

12
216
320
421
55
66

Configure the software

For this project we are using Python a robust and easy to learn language that is well suited to the Raspberry Pi. Python enables our project to use the GPIO pins which connect to the components on the game board and this is achieved via an external library, one of a few that will be used in this project.

 

Libraries

A library is a collection of code that can be included inside of our project. Typically a library is one of the many thousands that have been written, tested and approved by the Python community, but you can easily make your own library for personal use. Using a library is achieved by importing the contents of the library into the application, and this happens as so.


 

 

Typically you will use libraries that are already installed with your version of Python, but in this project we will be using a library that is not installed as standard. Which is pygame.

 

Pygame is a library of functions that can be used to build games in Python. It includes functions to handle sprites, sounds, images and keyboard events. In this project we will use it to play sounds for the pythons and resistors.

 

In order to use this library we need to install it on our Raspberry Pi, and for that we need to install the Python package manager, called PIP. PIP will have the latest versions of the libraries but it does not come as standard on a fresh Raspbian install. To install PIP, open a new terminal by double clicking on the LXTerminal desktop icon, or navigating to the LXMenu > Accessories > LXTerminal.

 

In the terminal issue the following command and press enter


 

When prompted for a password type it in and press enter. It will take a few moments for pip to be installed on your system. When completed keep the terminal window open and enter the following command.

 

 

Pip will now install the pygame library for this project and once complete you are now free to close the terminal window. With all of the software dependencies met we can now focus on the Python code that controls our game.

 

Python Code

When working in Python I like to use a set format for my code and that is as follows

 

Imports

Variables

Configurations

Functions (if any)

Main body of the code

 

And for this project I have followed that format.

 

Imports

Importing libraries is a vital skill to learn. It enables code written by others to be easily used in our projects. Giving us the convenience of growing our code with out the need to build concepts such as random numbers, GPIO functionality and GUI interfaces.

In the code we firstly import the libraries that are needed, and in the code snippet below I have added comments to explain what each import achieves.

 

 

With these imports completed we now need to create the variables that will contain the position of the resistors and Pythons on the board and their GPIO pin reference, the sounds used in the game , the GPIO pins used for each of the LED for our dice and also the GPIO pin used for the push button that triggers our dice.

 

 

Next we configure both Pygame and the GPIO pins that are used in the game. Pygame requires us to initialise both the actual library and the mixer functions and it looks like this

 

 

The GPIO configuration needs us to set the board layout, we can use the physical pin layout, where pin 1 is at the top left of the board, next to the micro SD slot. This is an easy layout to use and is great for beginners. For this article we will use the official Broadcom pin mapping, which is not a logical numbering system but is easy to use and is my preferred choice. To do this code.

 

 

Using the variables for the resistors and pythons that we created earlier we will now configure each of the pins to be an input, by which I mean that they will receive current when the switch is triggered. In order to protect the Raspberry Pi rather delicate GPIO we will be using an internal pull down resistor which buffers the pins to prevent any accidental damage.

 

 

With the inputs configured, we now do the same to the pins that make our digital dice, of which they are all output devices that receive power from the GPIO pins to make them light up.

 

 

Lastly on the setup we tell the pin used for d2 to turn off, as by default it is active and sending power out to any devices attached, we do this by doing the following.

 

 

Next we create a function which will handle the playback of the audio files used in the game. Our function takes an argument, which is the filename of the audio file. Once triggered the function loads the audio file into memory, and then plays the audio once per trigger. While the audio is playing the function checks to see if the audio is still playing and if so it waits until complete, before triggering again if needed.

 

 

Next we have a function which handles the roll of our digital dice. Once triggered it uses the random int function from the random library to pick a number between 1 and 6. Then using a series of conditional logic the number rolled is compared to each number 1 to 6 and when a match is found the corresponding LED are lit up, so if I roll a 5, 5 of the LED will light up.

 

 

Now we move to the final part of our code, this is the main body that is a series of if and else if conditional statements that look to see if any squares have been triggered or that the dice has been rolled. Once the trigger occurs, either the dice roll or audio file playback function is called and output via the Raspberry Pi.

 

 

And now we reach the end of this project. I hope that you have enjoyed yourself and learnt a little more about what the new B+ is capable of with just a few easy and cheap to purchase components.

The full code for this project, along with the image file for the game board is available via Github.

Filter Blog

By date: By tag: