Skip navigation

Raspberry Pi Projects

6 Posts authored by: biglesp    
Raspberry_Pi_Logo.svg.png

Raspberry Pi Projects - How does your IoT garden grow?

Join Les Pounder as he works on his IoT Garden! Watch him integrate technology into his garden and maintain the health of his favorite plants.

Check out our other Raspberry Pi Projects on the projects homepage

Previous Part
All Raspberry Pi Projects
Next Part - Coming Soon

Can our garden water itself?

In this project we continue our search to keep our garden well watered, but this time we start fresh with a new project...A self watering garden!

 

Re-using some of the kit from Project 1, in this project we introduce relays, 12V circuits and peristaltic pumps that will water our garden based on the soil moisture sensor from Project 1. All we need to do is keep a water butt full of water, either through rain or grey water collection!

 

IMG_20170920_151615.jpg

 

For this project you will need

 

Building the hardware

Aside from our Pi Zero W, the main player in this project is the Rasp.IO Analog Zero board, which provides us with an analog to digital converter, the MCP3008. Yes you can buy the chip on its own for only a few dollars / pounds, but the Analog Zero board is a convenient form factor that offers a “less wires” alternative.

The main sensor we are using is a simple soil moisture sensor from Velleman. The moisture sensor is a simple analog sensor which connects to the 3V and GND pins on the Analog Zero and the output of the sensor is connected to A0. The output from the sensor is in the form of a voltage from 0V to 3.3V (as we are using the 3.3V power from the Pi Zero GPIO) if there is no conductivity, i.e the soil is dry then no voltage is conducted, if the soil is wet then the soil will most likely conduct all of the voltage.

 

The other part of the project is a relay, used to control the 12V circuit for our peristaltic pump which will pump water from a water butt to our plants using a rotating motion to “squeeze” the water through the connected plastic hose. The relay is controlled from the GPIO of our Pi. In this case we connect the relay to 3V, GND and the Input of the relay to GPIO17.

 

The Analog Zero will take a little time to solder, and we shall also need to solder the pins for I2C and solder the 3V and GND pins for later. Once soldered, attach the Analog Zero to all 40 pins of the GPIO and then connect the sensor and relay board as per the diagram. You will also need to provide the 12V power supply to the peristaltic pump. The + connection from the 12V supply goes to the relay, via the normally open connection, the icon looks like an open switch.

 

DSC_2803.JPGDSC_2806.JPGIMG_20170920_151134.jpg

 

Build the project so that the wiring is as follows.

 

Circuit.png

 

Now connect up your keyboard, mouse, HDMI, micro SD card, and finally power up the Pi Zero W to the desktop. You will need to setup WiFi on your Pi Zero W, and make a note of the IP address for future use. Now open a terminal and enter the following command to configure SPI connection.

 

 

 

sudo raspi-config

 

 

Yes we can use the GUI “Raspberry Pi Configuration” tool found in the Preferences menu, but having raspi-config available to us over an SSH connection is rather handy should we need it.

 

 

Once inside raspi-config, we need to navigate to “Interfacing Options” then once inside this new menu go to the SPI option and press Enter, then select “Yes” to enable SPI. While not strictly necessary, now would be a great time to reboot to ensure that the changes have been made correctly. Then return to the Raspbian desktop. With the hardware installed and configured, we can now move on to writing the code for this project.

 

Writing the code

To write the code for this project we have used the latest Python editor, Thonny. Of course you are free to use whatever editor you see fit. You will find Thonny in the Main Menu, under the Programming sub-menu.

 

We start the code for this project by importing two libraries. The first is the GPIO Zero library, used for simple connections to electronic components. In this case we import the MCP3008 class for our Analog Zero board and then we import DigitalOutputDevice, a generic class to create our own output device.

 

from gpiozero import MCP3008, DigitalOutputDevice
import time

 

 

Now lets create two objects, the first, soil is used to connect our code to the Velleman soil moisture sensor, connected to A0 on the Analog Zero board, which is channel 0 on the MCP3008 ADC. Our second object is a connection to the relay, which is triggered by an output device, on GPIO17.

 

 

soil = MCP3008(channel=0)
relay = DigitalOutputDevice(17)

 

 

Moving on to the main part of the code we create a loop that will constantly run the code within it. Inside the loop the first line of code creates a variable, soil_check. This variable will store the value passed to it by the MCP3008, which is handled via the soil object. As this value is extremely precise we use the round function to round the returned value to two decimal places.

 

 

 while True:
    soil_check = round(soil.value,2)

 

 

Next we print the value stored in the variable to advise the user on the soil moisture level, handy for debugging the code! Then the code waits for one second.

 

 

   print('The wetness of the soil is',soil_check)
    time.sleep(1)

 

 

To check the soil moisture level we use an if conditional test. This will test the value stored in the soil_check variable against a hard coded value. In this case 0.1 was found to be very dry soil, but of course you are free to tinker and find the value right for your soil. If the soil is too dry then the condition is passed and the code is executed.

 

 

   if soil_check <= 0.1:

 

 

 

So what is the code that will be run if the condition is met? Well remember the relay object that we created earlier? We are going to use that object to turn on the relay, effectively closing the open switch and enabling the 12V circuit to be completed. This will trigger the peristaltic pump to life and pump water into the plants. Now for testing we set the time to two seconds, but in reality this will be much longer, depending on the length of hose that the water needs to pass through.  So when enough water has been passed  we need to turn off the relay, cutting the 12V circuit. The code then waits for 10 seconds before the loop repeats. Again these times are in seconds for test purposes, but in reality they would be in minutes.

 

       relay.on()
        time.sleep(2)
        relay.off()
        time.sleep(10)

 

So that’s it, we have now built and coded the project and it is ready to be tested. To test the code in Thonny, click on the “play” button located in the menu, or press F5. Now as there is no conductivity between the prongs of the soil moisture sensor the code will trigger and start to water the plants, obviously be careful with this!

Once checked, place something conductive between the two prongs and you will see that the output is just printed to the Python shell and no watering is triggered. When you are finished press the red stop button to halt the code.

 

So now that we have code, how can we make it executable? In order to do this there are two steps to take. First we need to add a line to the top of our Python code which instructs Python where to find the interpreter.

 

 

 

#!/usr/bin/python3

 

 

 

With that complete, we now need to go back to the terminal, and we need to issue a command to make the Python file executable from the terminal. The command is.

 

 

 

sudo chmod +x self_watering.py 

 

 

 

Now in the same terminal, launch the project by typing

 

 

./self_watering.py

 

 

 

Now the project will run in the terminal, checking our soil moisture levels and watering as necessary!

 

So how can we have the code run on boot? Well this is quite easy really. In the terminal we need to issue a command to edit our crontab, a file that contains a list of applications to be run at a specific time/date/occasion. To edit the crontab, issue the following command in the terminal.

 

 

sudo crontab -e

 

 

If this is the first time that you have used the crontab, then it will ask you to select a text editor, for this tutorial we used nano, but everyone has their favourite editor!

 

With crontab open, navigate to the bottom of the file and add the following line.

 

 

@reboot /home/pi/self_watering.py

 

 

Then press Ctrl + X to exit, you will be asked to save the file, select Yes.

 

Now reboot the Pi Zero W and for now ensure the soil moisture sensor has no connection between the prongs. After a about a minute, the project should be running, and your pump should start pumping water into the plants.

 

Power down the Pi Zero W, place it in a waterproof container along with a USB battery power source, ensure the soil sensor is out of the box. Place the project in your garden, and make sure the soil moisture sensor is firmly in the ground. Power up the Pi Zero W, and now your garden can now water itself!

Raspberry_Pi_Logo.svg.png

Raspberry Pi Projects - How does your IoT garden grow?

Join Les Pounder as he works on his IoT Garden! Watch him integrate technology into his garden and maintain the health of his favorite plants.

Check out our other Raspberry Pi Projects on the projects homepage

Previous Part
All Raspberry Pi Projects
Next Part

 

Project1B.JPG

 

Gardening is a delightful hobby, but it can be a chore and one particularly bothersome job is watering the garden. Water it too often and the plants can die, too little and they can also die! But surely technology can offer a solution to this age old problem? Well yes it can, and in this tutorial we shall be using the Raspberry Pi Zero W, the lower power Pi with added Bluetooth and WiFi, along with two sensors, a soil moisture sensor to check if our garden needs water and an Adafruit Flora UV sensor to measure the ultraviolet index of the sun. This data is then emailed to our preferred inbox via a Gmail account that we can use to send the messages on demand.

 

pebble.jpg

Our soil moisture sensor sensor will need an analog to digital converter to convert the analog voltage from our soil moisture sensor into something that the Pi can understand. In this case we shall be using the MCP3008 via an add on board from Rasp.IO called Analog Zero.

 

So let's get started by looking at the bill of materials for this project.

 


All of the code, and a detailed circuit diagram can be found on the Github page for this project. (Zip Download link)

 

Building the hardware

 

 

Rasp.io Analog Zero

Aside from our Pi Zero W, the main player in this project is the Rasp.IO Analog Zero board, which provides us with an analog to digital converter, the MCP3008. Yes you can buy the chip on its own for only a few dollars / pounds, but the Analog Zero board is a convenient form factor that offers a “less wires” alternative.

 

Vellemen Soil moisture SensorAdafruit Flora UV Sensor

The two sensors that we are using are a simple soil moisture sensor from Velleman, and an Adafruit Flora UV sensor based upon the SI1145 IC. The moisture sensor is a simple analog sensor, hence the use of the Analog Zero, but the Flora UV sensor uses I2C so we need to have access to those GPIO pins, which luckily the Analog Zero provides.

 

The Analog Zero will take a little time to solder, and we shall also need to solder the pins for I2C and solder the 3V and GND pins for later. We will also need to solder wires from the Flora UV sensor to attach to our Analog Zero.

Once soldered, attach the Analog Zero to all 40 pins of the GPIO and then connect the sensors as per the diagram.

 

Diagram of the circuit

 

Now connect up your keyboard, mouse, HDMI, micro SD card, and finally power up the Pi Zero W to the desktop. You will need to setup WiFi on your Pi Zero W, and make a note of the IP address for future use. Now open a terminal and enter the following command to configure SPI and I2C connections.

 

 

sudo raspi-config

 

 

raspi-config-main.png

Yes we can use the GUI “Raspberry Pi Configuration” tool found in the Preferences menu, but having raspi-config available to us over an SSH connection is rather handy should we need it.

 

 

Once inside raspi-config, we need to navigate to “Interfacing Options” then once inside this new menu go to the SPI option and press Enter, then select “Yes” to enable SPI. Then do the same for the I2C interface.

 

raspi-config-SPI.png

 

While not strictly necessary, now would be a great time to reboot to ensure that the changes have been made correctly. Then return to the Raspbian desktop. With the hardware installed and configured, we can now move on to installing the software library for this project.

 

Getting started with the software

We only have one software library to install for this project, and that is a Python library for working with the SI1145 sensor present on the Flora UV sensor. But before we install that library we need to ensure that our Pi Zero W has the latest system software installed. So open a terminal and type the following to update the list of installable software, and then install the latest software.

 

 

sudo apt update && sudo apt upgrade -y

 

With the software updated we now need to run another command in the terminal, and this command will install the Python library for our UV sensor.

 

 

git clone https://github.com/THP-JOE/Python_SI1145

 

 

Now change directory to that of the library we have just downloaded.

 

cd Python_SI1145


Now we need to run an install script so that the library will be available for later use. In the terminal type.

 

sudo python3 setup.py install


This library was designed to work with Python 2 but it installs cleanly and works with Python 3. But if you try out the built in examples you will need to add parentheses around the print statements, in line with Python 3 usage.

 


We can now close the terminal and instead let's open the Python editor, Thonny, found in the main menu under the Programming sub menu.

Once Thonny opens, immediately save your work as soil-uv-sensor.py

 

As ever with Python, we start by importing the libraries that we shall be using.

The first library is GPIO Zero, the easy to use Python library for working with the GPIO. From this library we import the MCP3008 class that will enable us to use the Analog Zero. Our second library is time, and we shall use that to add delays to our code, otherwise the project will spam our mailboxes with emails! Our third library is the SI1145 library that we shall use to read the data from our UV sensor. The fourth, fifth and sixth libraries are used to send emails, the smtplib enables Python to send an email, and the email.mime libraries are used to construct an email.

 

from gpiozero import MCP3008
import time
import SI1145.SI1145 as SI1145
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText


So we now move on and create two objects, one that is used to create a connection to the Flora UV sensor, called “sensor”. The other object is called “soil” and here we make a connection to the soil moisture sensor that is currently connected to A0 (Channel 0 of the MCP3008) via the Analog Zero.

 

 

sensor = SI1145.SI1145()
soil = MCP3008(channel=0)

 

 

Our main body of code is a while True loop that will ensure that our code runs continuously. Our first few lines in this loop will read the UV sensor and store the value into a variable, UV, which is then divided by 100 to give us a UV index value, which is then printed to the Python shell for debug purposes.

 

 

while True:
    UV = sensor.readUV()
    uvIndex = UV / 100.0
    print('UV Index:        ' + str(uvIndex))

 

 

In order to get the reading from our soil moisture sensor, we first need to make a new variable called soil_check and in this variable we store the value that is being sent A0 / Channel 0 of the MCP3008. Typically this would be read as a voltage, with 100% conductivity providing 3.3V But in this case the MCP3008 class from GPIO Zero returns a float value between 0.0 and 1.0 With 0.0 being no conductivity, so dry soil, and 1.0 meaning we have perfect conductivity and probably an over watered garden. You will also notice that we round the figure to two decimal places, as the value returned from the soil moisture sensor is quite precise and goes to many decimal places. We then print this value to the Python shell before sleeping for a second. Now for the purposes of testing the delay between checks is rather small, but in real life this delay would be measured in hours.

 

 

    soil_check = round(soil.value,2)
    print('The wetness of the soil is',soil_check)
    time.sleep(1)

 

 

So now that we have the data, let's use it. For this we need an if condition to check the value stored in soil_check against a hard coded value. In my case I used 0.1, but you are free to alter this to suit the plants / garden that you have. In my case I wanted to know if the soil became really dry, so any value equalling or lower than 0.1 will trigger the alert.

 

   if soil_check <= 0.1:


Now we start to construct the email that will be sent should the alert be raised. The first part of any email is to say who the email is from and who it is being sent to.

 

        fromaddr = "YOUR EMAIL ADDRESS"
        toaddr = "EMAIL ADDRESS TO SEND TO"


Next we construct our email as a MIME multipart message, in other words we can add more content to our email than a standard email. For this project we use multipart to enable the use of a subject line. But this could also be used with attachments such as video / images. Here we set up with our from and to email addresses, and then we set up the subject of the email.

 

        msg = MIMEMultipart()
        msg['From'] = fromaddr
        msg['To'] = toaddr
        msg['Subject'] = 'Garden requires water'

 

The next line we come across forms the body of our email, and it is made up from the readings taken by our sensors. These values are stored as floats in the variables soil_check and uvIndex and we then use concatenation to add them to a string readings which is then stored in the body.

 

        readings = 'Soil is '+str(soil_check)+'wet and the UV index is '+str(uvIndex)
        body = readings

 

 

Then we attach all of the email contents ready to be sent.

 

 

        msg.attach(MIMEText(body, 'plain'))

 

 

In order to send the message we need to have a connection to the Gmail server.

 

 

        server = smtplib.SMTP('smtp.gmail.com', 587)

 

 

So we now need to ensure that our connection is secure, so we use Transport Layer Security.

 

        server.starttls()

 

 

Now let's login to our Gmail account obviously you will need to use your own account.

 

 

server.login(fromaddr, "PASSWORD")

 

 

Our next step is to create a new variable text which will contain our email message converted to a string.

 

 

        text = msg.as_string()

 

 

We can now finally send the email using our email address, the address of the recipient, and the text that we have just converted.

 

        server.sendmail(fromaddr, toaddr, text)

 

 

Our last two lines of code close the connection to the Gmail server, and then instructs the project to wait, in this case for 10 seconds, but in reality this value will be much longer, otherwise you will receive lots of email spam!

 

 

        server.quit()
        time.sleep(10)

 

 

So that’s it, we have now built and coded the project and it is ready to be tested. To test the code in Thonny, click on the “play” button located in the menu, or press F5. Now as there is no conductivity between the prongs of the soil moisture sensor the code will trigger it to send an email. So check your inbox to see if it has arrived. Once checked, place something conductive between the two prongs and you will see that the output is just printed to the Python shell and no email is triggered. When you are finished press the red stop button to halt the code.

 

So now that we have code, how can we make it executable? In order to do this there are two steps to take. First we need to add a line to the top of our Python code which instructs Python where to find the interpreter.

 

 

#!/usr/bin/python3

 

 

With that complete, we now need to go back to the terminal, and we need to issue a command to make the Python file executable from the terminal. The command is.

 

 

sudo chmod +x soil_uv.py

 

 

Now in the same terminal, launch the project by typing

 

 

./soil_uv.py

 

 

Now the project will run in the terminal, printing output to the shell, and the emails should start to be sent as there is no connection between the two prongs of the sensor.

 

So how can we have the code run on boot? Well this is quite easy really. In the terminal we need to issue a command to edit our crontab, a file that contains a list of applications to be run at a specific time/date/occasion. To edit the crontab, issue the following command in the terminal.

 

 

sudo crontab -e

 

 

If this is the first time that you have used the crontab, then it will ask you to select a text editor, for this tutorial we used nano, but everyone has their favourite editor!

 

With crontab open, navigate to the bottom of the file and add the following line.

 

@reboot /home/pi/soil_uv.py

 

Then press Ctrl + X to exit, you will be asked to save the file, select Yes.

 

Now reboot the Pi Zero W and for now ensure the soil moisture sensor has no connection between the prongs. After a about a minute, the project should be running, and your inbox should start to receive emails.

 

WorkingProject.jpg

Power down the Pi Zero W, place it in a waterproof container along with a USB battery power source, ensure the soil sensor is out of the box, but keep the UV sensor inside the box, oh and make sure the container is transparent! Place the project in your garden, and make sure the soil moisture sensor is firmly in the ground. Power up the Pi Zero W, and now you can wait for your garden to tell you when it needs watering.

 

Next time...

In the next blog post in this series, we shall build a system to automatically water our garden when an alert is triggered.

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: