digital inputs and outputs on the raspberry pi - rs online · digital inputs and outputs on the...

32
Student Workbook 1 Digital Inputs and Outputs on the Raspberry Pi In this exercise you will use a digital “1-wire” sensor connected directly to the Raspberry Pi’s GPIO port to measure temperature, and investigate how the measured temperature can be used to control a digital output to simulate a central heating thermostat. You will then connect an LED driver chip to the Raspberry Pi and use it to display the measured temperature on a multi-digit seven segment LED display. The GPIO pins are located at one corner of the Raspberry Pi, as shown below. There are 26 pins in all, and they are used for a variety of different things. It isn’t important to remember what all the pins do, but it is important to note how they are numbered. If necessary, prepare your Raspberry Pi by performing the following tasks: Insert the prepared SD(HC) memory card into the card slot on the underside to the Raspberry Pi Connect the USB Keyboard and Mouse to the two USB sockets Connect the computer monitor or TV screen to the HDMI socket using the HDMI cable However, do not connect the power supply to the Micro USB socket at this stage.

Upload: doannguyet

Post on 24-Jul-2018

231 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Digital Inputs and Outputs on the Raspberry Pi - RS Online · Digital Inputs and Outputs on the Raspberry Pi ... The GPIO pins are located at one corner of the Raspberry Pi, as shown

Student Workbook

1

Digital Inputs and Outputs on the Raspberry Pi In this exercise you will use a digital “1-wire” sensor connected directly to the Raspberry Pi’s GPIO port to measure temperature, and investigate how the measured temperature can be used to control a digital output to simulate a central heating thermostat. You will then connect an LED driver chip to the Raspberry Pi and use it to display the measured temperature on a multi-digit seven segment LED display. The GPIO pins are located at one corner of the Raspberry Pi, as shown below. There are 26 pins in all, and they are used for a variety of different things. It isn’t important to remember what all the pins do, but it is important to note how they are numbered.

If necessary, prepare your Raspberry Pi by performing the following tasks:

Insert the prepared SD(HC) memory card into the card slot on the underside to the Raspberry Pi

Connect the USB Keyboard and Mouse to the two USB sockets

Connect the computer monitor or TV screen to the HDMI socket using the HDMI cable

However, do not connect the power supply to the Micro USB socket at this stage.

Page 2: Digital Inputs and Outputs on the Raspberry Pi - RS Online · Digital Inputs and Outputs on the Raspberry Pi ... The GPIO pins are located at one corner of the Raspberry Pi, as shown

Student Workbook

2

Step 1 – Take a temperature reading Please make sure your Raspberry Pi is turned off and the power supply disconnected before proceeding. In this exercise you will establish communication between your Raspberry Pi and the “1-wire” digital temperature sensor and then take a temperature reading. The temperature sensor you are going to use is a DS18B20 “1-wire” digital sensor. It is called a “1-wire” sensor because apart from power (VDD) and ground (GND) terminals, the only other terminal is a single data (D) terminal.

Your Raspberry Pi is already setup to connect with “1-wire” sensors via GPIO pin number 7. Build the circuit for this exercise by performing the following tasks:

Insert the DS18B20 sensor into the breadboard with its flat side facing left

Insert a 4700 Ohm (4K7, or 4.7K Ohm) resistor into the breadboard so that one end connects to pin number 3 (bottom terminal) on the DS18B20 and the and the other end connects to pin number 2 (middle terminal) on the DS18B20

Connect one end of the Red wire to pin number 1 on the GPIO header and connect the other end to the power rail on the right side of the breadboard

Connect one end of the Red wire to the power rail and connect the other end to pin number 3 (bottom terminal) on the DS18B20 sensor

Connect one end of the Black wire to pin number 6 on the GPIO header and connect the other end to the ground rail on the left side of the breadboard

Connect one end of the Black wire to the ground rail and connect the other end to pin number 1 (top terminal) on the DS18B20

Connect one end of the Orange wire to pin number 7 on the GPIO header and connect the other end to pin number 2 (middle terminal) on the DS18B20

Page 3: Digital Inputs and Outputs on the Raspberry Pi - RS Online · Digital Inputs and Outputs on the Raspberry Pi ... The GPIO pins are located at one corner of the Raspberry Pi, as shown

Student Workbook

3

The finished circuit is shown below.

Connect the power supply to the Micro USB socket on the Raspberry Pi and turn the power supply on

Allow your Raspberry Pi to boot up and then log in and launch the Graphical User Interface (GUI). If you’re not sure how to do this please follow the instructions in Step 2 of the Setup Guide

Page 4: Digital Inputs and Outputs on the Raspberry Pi - RS Online · Digital Inputs and Outputs on the Raspberry Pi ... The GPIO pins are located at one corner of the Raspberry Pi, as shown

Student Workbook

4

Double click on the LXTerminal icon on the desktop to open an LXTerminal window

Type “sudo modprobe w1-gpio” at the Linux command line and press Enter

Type “sudo modprobe w1-therm” at the Linux command line and press Enter

Type “cd /sys/bus/w1/devices/” at the Linux command line and press Enter

Type “ls” at the Linux command line and press Enter

This will display some numbers and letters similar to the following: 28-000005036f89 w1_bus_master1

Make a note of the 15 digit string of numbers and letters. This is the serial number of the temperature sensor you are using. In my case, the serial number was “28-000005036f89” but yours will be different

Type “cd xx-xxxxxxxxxxxx” at the Linux command line and press Enter

(where xx-xxxxxxxxxxxx is the serial number of your temperature sensor)

Type “cat w1_slave” at the Linux command line and press Enter This will take a temperature reading and display two lines of letters and numbers. The only part you are really interested is the end of the second line which should read “t=” followed by a 5 digit number

Page 5: Digital Inputs and Outputs on the Raspberry Pi - RS Online · Digital Inputs and Outputs on the Raspberry Pi ... The GPIO pins are located at one corner of the Raspberry Pi, as shown

Student Workbook

5

Take the 5 digit number at the end of the second line and divide it by 1000 to give you the temperature in deg C Therefore in my case the temperature was 23.375 deg C

You can continue to take temperature readings by re-entering the “cat w1_slave” command if you want (a shortcut for dong this is to press the “up” arrow on your keyboard and press Enter)

When you’re finished, click on “File” and then “Quit” to close the LXTerminal window

Shutdown your Raspberry Pi (refer back to Step 4 of the Setup Guide if you can’t remember how to do this)

Page 6: Digital Inputs and Outputs on the Raspberry Pi - RS Online · Digital Inputs and Outputs on the Raspberry Pi ... The GPIO pins are located at one corner of the Raspberry Pi, as shown

Student Workbook

6

Step 2 – Use the measured temperature to control a Digital Output In the previous part of this exercise you learned how to take a single temperature reading directly from the DS18B20 “1-wire” digital sensor using the Linux command line. Now you will write a Python program to take temperature readings from the DS18B20 “1-wire” digital sensor and use this measured temperature to control a digital output, thus modelling the behaviour of a central heating thermostat. Please make sure your Raspberry Pi is turned off and the power supply disconnected before proceeding. In this exercise you will write a Python program to continuously monitor the temperature, and use this measured temperature to control a digital output. This exercise follows on from the previous exercise, so start with the circuit from the previous exercise and perform the following tasks:

Connect one end of the Yellow wire to pin number 12 on the GPIO header and insert the other end into the breadboard

Note that one of the legs on the LED is slightly longer than the other. Insert the Yellow LED into the breadboard so that the longer of the two legs connects with the yellow wire

Insert a 47 Ohm resistor into the breadboard so that one end connects with the ground rail on the left side of the breadboard and the other end connects with the shorter leg of the Yellow LED

The finished circuit is shown below.

Page 7: Digital Inputs and Outputs on the Raspberry Pi - RS Online · Digital Inputs and Outputs on the Raspberry Pi ... The GPIO pins are located at one corner of the Raspberry Pi, as shown

Student Workbook

7

Connect the power supply to the Micro USB socket on the Raspberry Pi and turn the power supply on

Allow your Raspberry Pi to boot up and then log in and launch the Graphical User Interface (GUI). If you’re not sure how to do this please follow the instructions in Step 2 of the Setup Guide

In the previous part of this exercise you used the “modprobe” command to load the necessary kernel modules to support “1-wire” devices via the Raspberry Pi GPIO header. You will now set up the Raspberry Pi to load the necessary kernel modules each time it boots up so that you don’t have to manually load the kernel modules using the modprobe command. The “kernel” is the core of the operating system and connects application software to the hardware of the computer. It is a fundamental part of any operating system.

Click on the LXDE icon on the bottom left corner of the screen – this will display the “Start Menu”

Click on “Run” and then type “sudo leafpad /etc/modules” in the Run dialog box and click “OK” or press Enter

The “modules” file will open in leafpad

Page 8: Digital Inputs and Outputs on the Raspberry Pi - RS Online · Digital Inputs and Outputs on the Raspberry Pi ... The GPIO pins are located at one corner of the Raspberry Pi, as shown

Student Workbook

8

Add the following two new lines to the end of the file w1-gpio w1-therm

The modules file should now look like this

Click on “File” and then “Save” to save the file

Click on “File” and then “Quit” to exit Leafpad

Log out of the GUI desktop (refer back to Step 4 of the Setup Guide if you can’t remember how to do this)

You will now return to the Linux command line prompt

Type “sudo reboot” at the command line prompt and press Enter to reboot your Raspberry Pi

Allow your Raspberry Pi to reboot and then log in and launch the Graphical User Interface (GUI). If you’re not sure how to do this please follow the instructions in Step 2 of the Setup Guide

Click on the LXDE icon on the bottom left corner of the screen – this will display the “Start Menu”

Click on “Run”

Launch IDLE3 by typing “sudo idle3” in the Run dialog and click “OK” or press Enter

Page 9: Digital Inputs and Outputs on the Raspberry Pi - RS Online · Digital Inputs and Outputs on the Raspberry Pi ... The GPIO pins are located at one corner of the Raspberry Pi, as shown

Student Workbook

9

Open a new code window by clicking on “File” and then “New Window”

Type the following lines of Python code into this new window tfile=open (“/sys/bus/w1/devices/xx-xxxxxxxxxxxx/w1_slave”) This establishes communication with the DS18B20 “1-wire” digital temperature sensor (where xx-xxxxxxxxxxxx is the serial number of your temperature sensor) text=tfile.read() This takes a temperature reading and saves it in the variable “text” tfile.close() This closes communication with the temperature sensor print (text) This prints the temperature data on the Python Shell window

When you have entered the code, your code window should look like this:

Page 10: Digital Inputs and Outputs on the Raspberry Pi - RS Online · Digital Inputs and Outputs on the Raspberry Pi ... The GPIO pins are located at one corner of the Raspberry Pi, as shown

Student Workbook

10

Click on “File” and then “Save”

Save the file as “temp.py”

Page 11: Digital Inputs and Outputs on the Raspberry Pi - RS Online · Digital Inputs and Outputs on the Raspberry Pi ... The GPIO pins are located at one corner of the Raspberry Pi, as shown

Student Workbook

11

Click on “Run” and then “Run Module”

After a short delay the temperature data will appear on the Python Shell window

The temperature data displayed on the Python Shell window is very similar to that displayed in the Linux terminal window in the previous part of this exercise. You will now amend the code to make the output from the program more user friendly.

Click on the code window to bring it to the front

Insert the following lines after the “tfile.close” line

secondline=text.split(“\n”) [1] temperaturedata=secondline.split(“ “) [9] temperature=float(temperaturedata[2:] ) temperature=temperature/1000 These lines of code take the 5 digit number at the end of the second line of temperature data and divide it by 1000 to give you the temperature in deg C

Change the last line “print(text)” to the following

print(“Temperature : ”,temperature,“ deg C”) This prints the temperature as “Temperature : xx.xxx deg C” on the Python Shell window.

Page 12: Digital Inputs and Outputs on the Raspberry Pi - RS Online · Digital Inputs and Outputs on the Raspberry Pi ... The GPIO pins are located at one corner of the Raspberry Pi, as shown

Student Workbook

12

When you have entered the code, your code window should look like this:

Click “File” and then “Save” to save the code

Page 13: Digital Inputs and Outputs on the Raspberry Pi - RS Online · Digital Inputs and Outputs on the Raspberry Pi ... The GPIO pins are located at one corner of the Raspberry Pi, as shown

Student Workbook

13

Click on “Run” and then “Run Module”

After a short delay the temperature will appear on the Python Shell window

Now you are going to edit the code so that the temperature is measured once every second

Insert the following lines at the beginning of the code import time This imports the time Python library so you can program in delays print(“Press Ctrl+C to exit”) This prints the message “Press Ctrl+C to exit” on the Python Shell window while True: This sets up a “while” loop (see explanation below)

Indent all the rest of the code by inserting a “Tab” character at the beginning of each line

Add the following line at the end of the indented code

time.sleep(1) This causes execution of the program to pause for 1 second

Page 14: Digital Inputs and Outputs on the Raspberry Pi - RS Online · Digital Inputs and Outputs on the Raspberry Pi ... The GPIO pins are located at one corner of the Raspberry Pi, as shown

Student Workbook

14

In all the code you have written previously, the commands were executed one after the other, from the beginning of the file to the end. The “while” loop introduced above causes the indented code to be repeatedly executed while a condition is true. The condition used in the code above is simply “True”, which means that the indented code will be executed continuously (until the program is stopped by pressing “Ctrl+C”).

When you have finished editing the code, your code window should look like this:

Click on “File” and then “Save”

Click on “Run” and then “Run Module”

After a short delay, temperature measurements will start appearing on the Python Shell window every second

Try holding the temperature sensor between your finger and thumb to warm it up, and then let it go and watch the temperature fall again.

Page 15: Digital Inputs and Outputs on the Raspberry Pi - RS Online · Digital Inputs and Outputs on the Raspberry Pi ... The GPIO pins are located at one corner of the Raspberry Pi, as shown

Student Workbook

15

You should obtain results similar to the following

When you have finished, press Ctrl+C (i.e. press and hold the “Ctrl” key, and at the same time press the “C” key) to exit the program

Click anywhere on the code window to bring it to the front Finally, you are going to modify the code to model the behaviour of a central heating thermostat by using the measured temperature to control a digital output. Choose a temperature a few degrees above the minimum you have previously measured - this will be your target temperature. I’m going to choose 27 deg C

Insert the following lines of Python code after the line “import time” import RPi.GPIO as GPIO GPIO.setmode(GPIO.BOARD) GPIO.setup(12, GPIO.OUT) GPIO.output(12, 0) This code sets up GPIO pin 12 as an output and sets its initial state to “0” (i.e. “off”)

Page 16: Digital Inputs and Outputs on the Raspberry Pi - RS Online · Digital Inputs and Outputs on the Raspberry Pi ... The GPIO pins are located at one corner of the Raspberry Pi, as shown

Student Workbook

16

Insert the following lines after the “print(“Temperature : “, temperature, “ deg C”) line if (temperature < 27): GPIO.output(12,1) else: GPIO.output(12,0) This is an “if … else” statement. If the test condition contained within the brackets is true, the indented code immediately following the “if” statement is executed. If the condition contained within the brackets is not true, the indented code immediately following the “else” statement is executed In other words, when the measured temperature is less than 27 deg C the LED will light up, but when the measured temperature is equal to or higher then 27 deg C, the LED will go out. This is similar to the operation of a central heating thermostat, where the heating is switched on when the temperature drops below a certain value, and switched off again when the temperature reaches or exceeds that value.

When you have finished editing the code, your code window should look like this:

Click on “File” and then “Save”

Click on “Run” and then “Run Module”

After a short delay, temperature measurements will start appearing on the Python Shell window every second, and the LED should light up

Hold the temperature sensor between your finger and thumb until the LED goes out.

This represents switching the heating on.

Page 17: Digital Inputs and Outputs on the Raspberry Pi - RS Online · Digital Inputs and Outputs on the Raspberry Pi ... The GPIO pins are located at one corner of the Raspberry Pi, as shown

Student Workbook

17

When the LED goes out, release the temperature sensor and watch as the temperature falls. Eventually the temperature will fall below the target value and the LED will light up again. When this happens, grip the temperature sensor between finger and thumb again until the LED goes out

You should find that you are able to maintain the temperature within a few degrees of the target temperature as demonstrated by the following screen shot

When you have finished, press Ctrl+C (i.e. press and hold the “Ctrl” key, and at the same time press the “C” key) to exit the program

Click anywhere on the code window to bring it to the front

Close the code window by clicking on “File” and then “Close”

If you have made any changes to the code since the last time you saved you will be asked if you want to save before closing

Click “Yes” if you want to save your changes, or “No” if you want to close without saving

Click on “File” and then “Exit” to close the Python Shell window and exit IDLE3

Shutdown your Raspberry Pi (refer back to Step 4 of the Setup Guide if you can’t remember how to do this)

Page 18: Digital Inputs and Outputs on the Raspberry Pi - RS Online · Digital Inputs and Outputs on the Raspberry Pi ... The GPIO pins are located at one corner of the Raspberry Pi, as shown

Student Workbook

18

Step 3 – Display the measured temperature on a 7 segment LED display In the previous part of this exercise you measured the temperature using a DS18B20 “1-wire” digital sensor, displayed the measured temperature on the Python Shell window, and used the measured temperature to control a digital output on the Raspberry Pi’s GPIO port. In this part of the exercise you are going to display the measured temperature on a 4 digit LED display like the type shown below.

This LED display module has 36 pins, which is far too many to connect directly to the Raspberry Pi’s GPIO port. You will use a LED display driver chip to “drive” the LED display and send data to the LED display driver chip from the Raspberry Pi’s GPIO port. The chip you will use is a MAX7219 serially interfaced 8-Digit LED display driver chip

This chip can drive up to 8 LED digits, but you will use it to drive 4 digits. The MAX7219 chip communicates with the Raspberry Pi using the Serial Peripheral Interface (SPI), which is similar in many ways to the I2C protocol you have used in some of the other exercises. As its name suggests, SPI a type of SERIAL data interface (or BUS), where the bits of data (0’s and 1’s) are sent down the same wires one after the other. The alternative would be to use a PARALLEL data interface, where you would have a separate wire for each bit of data. The connection between the Raspberry Pi and the MAX7219 chip will use just three wires (DIN, LOAD and CLK).

Page 19: Digital Inputs and Outputs on the Raspberry Pi - RS Online · Digital Inputs and Outputs on the Raspberry Pi ... The GPIO pins are located at one corner of the Raspberry Pi, as shown

Student Workbook

19

Please make sure your Raspberry Pi is turned off and the power supply disconnected before proceeding. In this exercise you will display the measured temperature on a 4 digit LED display. This exercise follows on from the previous exercise, so start with the circuit from the previous exercise and perform the following tasks:

Insert the MAX7219 chip into the breadboard so that it straddles the gap down the centre of the breadboard. Note that the end of the chip with the notch in it should be nearest the yellow LED

Connect one end of the Grey wire to pin number 23 on the GPIO header and connect the other end to pin number 13 on the MAX7219 chip (bottom right)

Connect one end of the Green wire to pin number 24 on the GPIO header and connect the other end to pin number 12 on the MAX7219 chip (bottom left)

Connect one end of the Blue wire to pin number 19 on the GPIO header and connect the other end to pin number 1 on the MAX7219 chip (top left)

Connect one end of the Black wire to pin number 4 on the MAX7219 chip and connect the other end to the ground rail on the left side of the breadboard

Connect one end of the Black wire to pin number 9 on the MAX7219 chip and connect the other end to the ground rail on the left side of the breadboard

Connect one end of the Black wire to pin number 19 on the MAX7219 chip and connect the other end to the power rail on the right side of the breadboard

Insert the 33KOhm (33000 Ohm) resistor into the breadboard between pins 18 and 19 on the MAX7219 chip.

Insert the 4 digit LED display module into another breadboard so that it straddles the gap down the centre of the breadboard.

Connect one end of the Grey wire to pin number 2 on the MAX7219 chip and connect the other end to pin number 32 on the LED display module

Connect one end of the Grey wire to pin number 6 on the MAX7219 chip and connect the other end to pin number 23 on the LED display module

Connect one end of the Grey wire to pin number 7 on the MAX7219 chip and connect the other end to pin number 22 on the LED display module

Connect one end of the Grey wire to pin number 11 on the MAX7219 chip and connect the other end to pin number 31 on the LED display module

Using four Orange wires, connect pin number 23 on the MAX7219 chip to pins 2, 6, 11, and 15 on the LED display module

Using four Red wires, connect pin number 22 on the MAX7219 chip to pins 4, 9, 13, and 18 on the LED display module

Using four Yellow wires, connect pin number 21 on the MAX7219 chip to pins 1, 5, 10, and 14 on the LED display module

Using four Green wires, connect pin number 20 on the MAX7219 chip to pins 3, 8, 12, and 17 on the LED display module

Page 20: Digital Inputs and Outputs on the Raspberry Pi - RS Online · Digital Inputs and Outputs on the Raspberry Pi ... The GPIO pins are located at one corner of the Raspberry Pi, as shown

Student Workbook

20

Using four Purple wires, connect pin number 17 on the MAX7219 chip to pins 7, 16, 26, and 35 on the LED display module

Using four Brown wires, connect pin number 16 on the MAX7219 chip to pins 19, 24, 28, and 33 on the LED display module

Using four Blue wires, connect pin number 15 on the MAX7219 chip to pins 21, 27, 30, and 36 on the LED display module

Using four White wires, connect pin number 14 on the MAX7219 chip to pins 20, 25, 29, and 34 on the LED display module

The finished circuit is shown below (connections between the MAX7219 chip and the LED display module not shown for clarity)

Page 21: Digital Inputs and Outputs on the Raspberry Pi - RS Online · Digital Inputs and Outputs on the Raspberry Pi ... The GPIO pins are located at one corner of the Raspberry Pi, as shown

Student Workbook

21

Connect the power supply to the Micro USB socket on the Raspberry Pi and turn the power supply on

Allow your Raspberry Pi to boot up and then log in and launch the Graphical User Interface (GUI). If you’re not sure how to do this please follow the instructions in Step 2 of the Setup Guide

First of all you need to enable the SPI bus on the Raspberry Pi so that the Raspberry Pi can communicate with the MAX7219 chip.

Click on the LXDE icon on the bottom left corner of the screen – this will display the “Start Menu”

Click on “Run” and then type “sudo leafpad /etc/modprobe.d/raspi-blacklist.conf” in the Run dialog box and click “OK” or press Enter

The file “raspi-blacklist.conf” will open in Leafpad

Page 22: Digital Inputs and Outputs on the Raspberry Pi - RS Online · Digital Inputs and Outputs on the Raspberry Pi ... The GPIO pins are located at one corner of the Raspberry Pi, as shown

Student Workbook

22

Comment out the line “blacklist spi-bcm2708” by inserting a “#” at the start of the line

Click on “File” and then “Save” to save the file

Click on “File” and then “Quit” to exit Leafpad

Log out of the GUI desktop (refer back to Step 4 of the Setup Guide if you can’t remember how to do this)

You will now return to the Linux command line prompt

Type “sudo reboot” at the command line prompt and press Enter to reboot your Raspberry Pi

Allow your Raspberry Pi to reboot and then log in and launch the Graphical User Interface (GUI). If you’re not sure how to do this please follow the instructions in Step 2 of the Setup Guide

Page 23: Digital Inputs and Outputs on the Raspberry Pi - RS Online · Digital Inputs and Outputs on the Raspberry Pi ... The GPIO pins are located at one corner of the Raspberry Pi, as shown

Student Workbook

23

Double click on “LXTerminal” to open a Terminal window and type “cd /dev” at the Linux command line prompt and press Enter. Then and type “ls spi*” at the Linux command line prompt and press Enter. You should see two SPI items listed – “spidev0.0” and “spidev0.1”

The SPI bus on your Raspberry Pi is now enabled. Now you need to make sure that all the software on your Raspberry Pi is up to date

Type “cd /home/pi” at the Linux command line prompt and press Enter. This will take you back to your home directory.

Type “sudo apt-get update” at the Linux command line prompt and press Enter

This will download an up to date list of all the available Raspberry Pi software

Type “sudo apt-get upgrade” at the Linux command line prompt and press Enter

This will download up to date versions of all the software installed on your Raspberry Pi

The “update” and “upgrade” commands may take a few minutes to complete – please be patient! Please note - if you get an error message which says “Unable to fetch some archives….” you may need to run the “update” and “upgrade” commands more than once, but you should always run the “update” command followed by the “upgrade” command.

Page 24: Digital Inputs and Outputs on the Raspberry Pi - RS Online · Digital Inputs and Outputs on the Raspberry Pi ... The GPIO pins are located at one corner of the Raspberry Pi, as shown

Student Workbook

24

Now you need to install some software to give you access to the SPI bus from Python.

Type “sudo apt-get install python-dev” at the Linux command line prompt and press Enter

When you are prompted, type “Y” and press Enter to continue with the installation

This may take a few minutes to complete

Page 25: Digital Inputs and Outputs on the Raspberry Pi - RS Online · Digital Inputs and Outputs on the Raspberry Pi ... The GPIO pins are located at one corner of the Raspberry Pi, as shown

Student Workbook

25

When installation has finished and you are returned to the Linux command line prompt type “git clone git://github.com/doceme/py-spidev” and press Enter

This will download some Python code from GitHub

Page 26: Digital Inputs and Outputs on the Raspberry Pi - RS Online · Digital Inputs and Outputs on the Raspberry Pi ... The GPIO pins are located at one corner of the Raspberry Pi, as shown

Student Workbook

26

When you are returned to the Linux command line prompt type “cd py-spidev” and press Enter.

Page 27: Digital Inputs and Outputs on the Raspberry Pi - RS Online · Digital Inputs and Outputs on the Raspberry Pi ... The GPIO pins are located at one corner of the Raspberry Pi, as shown

Student Workbook

27

Type “sudo python setup.py install” at the Linux command line prompt and press Enter

Click on “File” and then “Quit” to close the LXTerminal window You should now be ready write a Python program to test the operation of the LED display module before using it to display the temperature.

Click on the LXDE icon on the bottom left corner of the screen – this will display the “Start Menu”

Click on “Run”

Launch IDLE by typing “sudo idle” in the Run dialog and click “OK” or press Enter

Note that you must use IDLE, and not IDLE3 for this part of the exercise because the “spidev” package you installed only supports Python 2

Open a new code window by clicking on “File” and then “New Window”

Type the following lines of Python code into this new window

import spidev This imports the spidev Python library so you can access the SPI bus import time This imports the time Python library so you can program in delays

Page 28: Digital Inputs and Outputs on the Raspberry Pi - RS Online · Digital Inputs and Outputs on the Raspberry Pi ... The GPIO pins are located at one corner of the Raspberry Pi, as shown

Student Workbook

28

spi=spidev.SpiDev() spi.open(0,0) This establishes communication with the MAX7219 chip via its SPI bus and assigns the name “spi” to the SPI bus spi.writebytes([0x0F,0x01]) This instructs the MAX7219 chip to enter “test mode”. In test mode all the segments of the LED display module are illuminated time.sleep(1) This causes execution of the program to pause for 1 second spi.writebytes([0x0F,0x00]) spi.writebytes([0x0C,0x01]) This instructs the MAX7219 chip to exit “test mode” and resume normal operation spi.writebytes([0x09,0x0F]) This instructs the MAX7219 chip to use the correct decode mode spi.writebytes([0x0B,0x03]) This instructs the MAX7219 chip that you are using a 4 digit LED display module (the chip can support up to 8 digits) spi.writebytes([0x0A,0x0F]) This sets the brightness of the LED display module (0c0F is the maximum value) spi.writebytes([0x01,0x01]) spi.writebytes([0x02,0x02]) spi.writebytes([0x03,0x03]) spi.writebytes([0x04,0x04]) This instructs the MAX7219 chip to display the number “1234” on the LED display module time.sleep(3) This causes execution of the program to pause for 3 seconds spi.writebytes([0x0C,0x00]) This instructs the MAX7219 chip to turn the LED display module off spi.close() This deactivates the SPI bus

Click on “File” and then “Save”

Save the file as “7segtest.py”

Page 29: Digital Inputs and Outputs on the Raspberry Pi - RS Online · Digital Inputs and Outputs on the Raspberry Pi ... The GPIO pins are located at one corner of the Raspberry Pi, as shown

Student Workbook

29

Your code window should look like this (but note that I have added comments to the code to remind me what each command does)

The numbers starting with “0x” in the Python code in this exercise are “hexadecimal” numbers (number base 16) and are a shorthand way of writing binary. Hexadecimal numbers consist of the symbols 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E and F and are always preceded by “0x”.

Hexadecimal Binary

0 0000

1 0001

2 0010

3 0011

4 0100

5 0101

6 0110

7 0111

8 1000

9 1001

A 1010

B 1011

C 1100

D 1101

E 1110

F 1111

Therefore the hexadecimal number 0x0F is just a shorthand way of writing the binary number 00001111

Page 30: Digital Inputs and Outputs on the Raspberry Pi - RS Online · Digital Inputs and Outputs on the Raspberry Pi ... The GPIO pins are located at one corner of the Raspberry Pi, as shown

Student Workbook

30

Click on “Run” and then “Run Module”

All the segments on the LED will light up briefly and then the number “1234” will be displayed for 3 seconds.

Click anywhere on the code window to bring it to the front

Select all the code using the mouse and then click on “Edit” and then “Copy”

Click anywhere on the Python Shell window and then click on “File” and then “Open” and open the file “temp.py” you saved in the previous part of this exercise

Click on the window containing the “temp.py” code and go to the end of the file

Click on “Edit” and then “Paste” to paste the LED display module code into the “temp.py” file.

Click on “File” and then “Save As” and call the file “thermostat.py”

You can now close the code window containing the “7segtest.py” code The “thermostat.py” code window now contains all the code from the “temp.py” program, and all the code from the “7segtest.py” program and so should contain (almost) everything you need to be able to display the measured temperature on the LED display module The only changes required to the code are the formatting of the temperature data into individual digits (digit1, digit2, digit3 and digit4) so that the digits can be displayed on the LED display module, and the addition of “try” and “except” blocks to allow some “housekeeping” tasks to be performed when “Ctrl+C” is pressed to terminate the program.

Page 31: Digital Inputs and Outputs on the Raspberry Pi - RS Online · Digital Inputs and Outputs on the Raspberry Pi ... The GPIO pins are located at one corner of the Raspberry Pi, as shown

Student Workbook

31

Edit the existing code by copying, pasting, deleting and inserting until your code listing looks like this

I have indicated where new lines of code have been inserted, and where existing lines of code have been changed to help you, but you do not need to include these comments

import time import spidev import RPi.GPIO as GPIO GPIO.setmode(GPIO.BOARD) GPIO.setup(12,GPIO.OUT) GPIO.output(12,0) # activate SPI bus spi=spidev.SpiDev() spi.open(0,0) # Enter display test mode spi.writebytes([0x0F,0x01]) # pause for 1 second time.sleep(1) # Resume normal operation spi.writebytes([0x0F,0x00]) spi.writebytes([0x0C,0x01]) # set decode mode spi.writebytes([0x09,0x0F]) # set scan limit spi.writebytes([0x0B,0x03]) # set intensity spi.writebytes([0x0A,0x0F]) print("Press Ctrl+C to exit") try: # new while True: tfile=open("/sys/bus/w1/devices/28-000005036f89/w1_slave") text=tfile.read() tfile.close() secondline=text.split("\n")[1] temperaturedata=secondline.split(" ")[9] temperature=float(temperaturedata[2:]) temperature=temperature/1000 digit1=int(temperaturedata[2]) # new digit2=(128+int(temperaturedata[3])) # new digit3=int(temperaturedata[4]) # new digit4=int(temperaturedata[5]) # new # display the temperature # changed spi.writebytes([0x01,digit1]) # changed spi.writebytes([0x02,digit2]) # changed spi.writebytes([0x03,digit3]) # changed spi.writebytes([0x04,digit4]) # changed if (temperature < 27): GPIO.output(12,1) else: GPIO.output(12,0) time.sleep(1) except KeyboardInterrupt: # new GPIO.output(12,0) # new GPIO.cleanup() # new # turn the LED display off spi.writebytes([0x0C,0x00]) # deactivate the SPI bus spi.close()

Page 32: Digital Inputs and Outputs on the Raspberry Pi - RS Online · Digital Inputs and Outputs on the Raspberry Pi ... The GPIO pins are located at one corner of the Raspberry Pi, as shown

Student Workbook

32

Click on “File” and then “Save”

Click on “Run” and then “Run Module”

All the segments on the LED will light up briefly and then the temperature will be displayed

Hold the temperature sensor between your finger and thumb and watch the temperature increase. The yellow LED will go out when the temperature reaches 27 deg C

When the yellow LED goes out, release the temperature sensor and watch as the temperature falls. Eventually the temperature will fall below the target value and the yellow LED will light up again

When you have finished, press Ctrl+C (i.e. press and hold the “Ctrl” key, and at the same time press the “C” key) to exit the program

Click anywhere on the code window to bring it to the front

Now see if you can edit the code so that the yellow LED is illuminated when the temperature is above the target value, and not illuminated when the temperature is below the target value. This system might be used to control a cooling fan (for example on your computer’s CPU or graphics card) where the cooling fan is turned on when the temperature reaches a certain value, and turned off again when the temperature drops below value

When you have finished running your modified code, press Ctrl+C (i.e. press and hold the “Ctrl” key, and at the same time press the “C” key) to exit the program

Click anywhere on the code window to bring it to the front

Close the code window by clicking on “File” and then “Close”

If you have made any changes to the code since the last time you saved you will be asked if you want to save before closing

Click “Yes” if you want to save your changes, or “No” if you want to close without saving

Click on “File” and then “Exit” to close the Python Shell window and exit IDLE3

Shutdown your Raspberry Pi (refer back to Step 4 of the Setup Guide if you can’t remember how to do this)