Articles From Sean McManus
Filter Results
Cheat Sheet / Updated 03-14-2022
The Raspberry Pi is perhaps the most inspiring computer available today. It comes with the tools you need to start making your own software, and you can connect your own electronic inventions to it. These tips show you how to discover and install great free software on your Raspberry Pi and how to program in Scratch.
View Cheat SheetArticle / Updated 11-08-2017
The Raspberry Pi can play back full HD 1080p video, which makes it ideal as the heart of a cheap and low-powered media center. The NOOBS software includes two Linux distributions, both based on Kodi, that turn your Raspberry Pi into a media center. The choices are OSMC and LibreELEC. Because they’re both based on the Kodi core, they have many similarities. LibreELEC uses the default Kodi design (or skin), so it's more likely to resemble other Kodi systems you have used. It's also a more lightweight option, so it may perform better on lower-powered Raspberry Pi models. To make it easier, you can choose the default Kodi skin by clicking Settings on the left, choosing Interface from the menu that appears, and then choosing Skin. Click Skin in the main part of the screen to open the options and choose Estuary, which is the Kodi default. You can change back to the OSMC skin from Estuary by clicking the Cogwheel icon at the top of the menu on the left, choosing Interface Settings from the menu that appears, hovering over Skin on the left, and then clicking Skin in the main part of the screen. You can exit any of the menus by pressing Esc. To start setting up your media center, create an SD or MicroSD card with NOOBS Lite on it, and then use that card to install LibreELEC. When you first boot up LibreELEC, you'll be guided through its main settings, including its name on the network, the network connection itself, and the remote access settings (so that you can access files on your device over the network).
View ArticleArticle / Updated 11-08-2017
The Kodi screen on your Raspberry Pi looks like what you see here. LibreELEC uses Kodi’s simple interface, which is designed to work with only a remote control. If you’re using a remote control, you should find the interface intuitive. The menu on the left side of the screen gives you access to the different content types, including movies, TV shows, music, and music videos. When you hover the mouse pointer over one of these options, the main screen area on the right shows you options and submenus for accessing your content. The Music section, for example, shows you categories you can browse, recently played albums, recently added albums, random albums, random artists, unplayed albums, and most played albums. You can use the cursor keys to move around the options; or the mouse, with the scroll wheel moving between the options within a menu. To exit a menu, press the Escape key. To select an item and start to play it, simply click it. You can pause playback by tapping the spacebar, and tap Escape to get back to the menu. To use the TV and radio features, you'll need to have a separate tuner device and TV signal decoding software. At the top of the menu on the left are buttons for switching off your Pi, accessing the settings menus (the Cogwheel icon), and searching for content (the magnifying glass).
View ArticleArticle / Updated 11-08-2017
Need to do some tweaking? You can change the settings on your Raspberry Pi easily enough. The cogwheel at the top of the main menu gives you access to the settings for Kodi, divided into several sections. They include, among others: Player settings, covering options such as whether the next song or video plays automatically, whether there is cross-fading between songs, and the use of subtitles. Media settings, which enable you to manage your sources of media in the library and choose information providers for artist and album information. Interface settings, which enable you to choose a skin (or design) for Kodi, your region, and a screensaver. If you install a screensaver add-on, you'll need to enable it here. System settings, which can be used to choose the correct audio output device, configure notification sounds in Kodi, and configure power and the Internet connection. LibreELEC, which includes options for managing the Internet connections available to the system and for enabling Secure Shell (SSH) for remote access to your Pi. File Manager, which enables you to copy files between different folders and storage devices. By default, the sound is set to pass through your HDMI cable. If you want to use your Raspberry Pi’s audio output (and speakers) but you’re using HDMI for your screen, you’ll need to change the audio setting from HDMI to Analog. You’ll find this option on Kodi's System Settings menu. When you’re viewing the settings menu, select Audio on the left and select Audio Output.
View ArticleArticle / Updated 11-08-2017
You can use your Raspberry Pi to compose your own tunes or Sonic Pi can also use samples, which are snippets of music that you can manipulate, such as by changing their speed or adding effects to them. Sonic Pi includes a wide range of samples, and you can see a list of them by showing the Help pane and then using the Sample button in the bottom left. They're especially useful for adding drum loops to your music. Here’s a favorite: sample :loop_industrial Put that into a new buffer and click Run to hear it. You can speed it up or slow it down by changing its rate. Here’s how you make it play at half its normal speed: sample :loop_industrial, rate: 0.5 You can repeat that sample to make a continuous rhythm. Similar to composing your own music, you can use the sleep command to put a pause between each repetition. Samples can be different lengths, however, which can make it difficult to work out how long to sleep. Luckily, Sonic Pi provides a feature in the language to stretch a sample over a certain number of beats, which solves this problem. You can use it like this: loop do sample :loop_industrial, beat_stretch: 2 sleep 2 end Now the sample is stretched over 2 beats, and there is a 2-beat pause between each repetition. As a result, you can hear a continuous rhythm. As you saw when experimenting with live loops, you can change the tempo with the use_bpm command.
View ArticleArticle / Updated 11-08-2017
You can access GPIO pins on your Raspberry Pi with Python. Unlike Scratch's graphic-based program blocks, Python uses entirely text-based instructions. Its great power is that the basic Python language can be extended to do more things by the use of libraries. These are functions that can be written in Python or any other language to extend what Python can do. When using Python to access the GPIO pins, you have a number of different libraries you could choose that can give you access to them. They can provide not only normal input/output access but also access to some of the special functions or capabilities of certain pins. In the early days of the Raspberry Pi, the only access to the GPIO pins was if you were running in Supervisor, or Root, mode. Fortunately, this has now been changed so that you can run in normal User mode with most libraries. While the newly introduced Thonny Python IDE (Integrated Development Environment) is popular with beginners, our preferred environment for writing Python is IDLE3 (it has more features), but either can be used. IDLE3 and Thonny can both be accessed from the main Desktop Raspberry menu. So, pick the one of your choice and create a new file, and then type in the program you see below. Remember that, in Python, the case of a word matters as does the spaces at the start of a line, so be sure to get them right; otherwise, you will get errors when trying to run your code. #!/usr/bin/python3 import time import RPi.GPIO as io # using RPi.GPIO io.setmode(io.BCM) io.setup(4,io.OUT) # make pin into an output print("LED blinker - By Mike Cook") print("Ctrl C to quit") while True: io.output(4,0) time.sleep(0.30) io.output(4,1) time.sleep(0.30) Save the file and run it. Your LED blinks just like the Scratch example. Take a look at the code line by line. The program starts by importing the support packages you need. In this case, it’s the time package used to achieve a Delay, or Wait, function, and the RPi.GPIO package to access the GPIO pins. Note here that a lot of examples use as GPIO in the import statement — but you can use the simpler and shorter as io because it reduces the amount of typing and you don't have to keep switching to uppercase. Then you have to tell the library what sort of numbering system you want to use. We’re using the now-standard BCM system. The next line tells the GPIO pins that you want to use Pin 4 as an output. The setup method takes two values: the pin number and a number that tells the library to make that pin an output. This is conveniently hidden by the library, by using a predefined constant that’s defined in the library — that’s why it’s prefixed with io. Next, the loop forever of Scratch is carried out in Python with the use of the while True statement, with all statements in this loop indented. This loop then commands the GPIO Pin 4 to be a 0, turning the LED off. Then there’s a delay (or sleep) for 300mS, followed by turning the LED on by making Pin 4 go high. Finally, there’s another delay, so you can see the LED in the On state. A common mistake is to leave out this last delay; as a result, the LED looks to be off all the time. So, controlling a GPIO output is very simple. Now, on to the second example of a switch-controlled blink speed. This is shown below, so open up a new file and type it in. #!/usr/bin/python3 io.setmode(io.BCM) io.setup(4,io.OUT) # make pin into an output io.setup(24,io.IN, pull_up_down=io.PUD_UP) # make pin an input print("LED blinker - By Mike Cook") print("Ctrl C to quit") while True: io.output(4,0) if io.input(24) == 1: time.sleep(0.30) else : time.sleep(1.00) io.output(4,1) if io.input(24) == 1: time.sleep(0.30) else : time.sleep(1.00) This code has the same commands for the output pin, but the input pin setup is new. This command has three parameters: the number of the pin to use, a number in the form of a constant defined by the library, specifying that this pin should function as an input, and, finally, some commands telling the computer to activate the internal pull-up resistor (although, to our ears, PUD_UP sounds more like a mother calling children to tell them their pudding is being served). The LED is first turned off as before, and then the input from the push button is read by the input(24) method, which returns a value of 0 or 1, depending on whether the pin is connected to the ground. This returned value is then compared to 1, and if it’s equal, a 300mS delay is made; otherwise, it produces a 1-second delay. The LED is turned on, and the Conditional Delay code is repeated.
View ArticleArticle / Updated 11-08-2017
There’s a new kid on the block when it comes to accessing the GPIO pins in Python on your Raspberry Pi: the GPIO Zero library. Don't confuse this with the Pi Zero — the two are not related. The GPIO Zero library takes the class method approach to control, as opposed to the function method approach of RPi.GPIO and other, similar libraries. Pins become Python objects, which must be set up before use. Despite this complication, using this system is easy. For example, for an LED blink example, you can use this code #!/usr/bin/python3 import time, os import gpiozero as io # using LED zero led = io.LED(4) # make pin 4 into an output print("LED blinker using gpiozero - By Mike Cook") print("Ctrl C to quit") while True: led.on() time.sleep(0.30) led.off() time.sleep(0.30) The library uses only the BCM method of pin numbering, so there’s no need to tell the library what system to use. An output pin is known as an LED, irrespective of whether that pin controls an LED, a motor, or a chip. So, the line that makes the pin an output is io.LED(4). This code segment returns a reference to the class object. Classes and objects are a way to get the same piece of code to handle different specific objects — in this particular case, different GPIO pins. In order to know what it has to do, each thing/pin must be declared separately, and when it is, the program gets a code number to use to identify which specific thing it has to handle. That code number is placed into a variable called led in code above, but could be called anything. (This variable is known as the instance reference.) The class has methods associated with it — things it can do, in other words — and these are called up by writing the instance reference variable name, followed by a period or dot, followed by the method name. So, turning an LED on or off is a simple process — you just write led.on() or led.off(). However, in a way, this is a bit limiting. For example, you cannot send a number in a variable that’s used to turn the LED on or off — it has to be specifically spelt out as a method name. This is a limitation of how GPIO Zero is written, not a limitation of using classes. There are ways round this, but at this point, the simple system gets rather complex. In fact, the code above is written in a way that it looks a lot like the earlier listings. The same thing could simply be written as shown. import gpiozeroled = LED(4) led.blink() And that’s all you need. That last statement can have some parameters in it to control the blink rate — so, for example, to exactly match our other examples that last line could be: led.blink(on_time = 0.3, off_time = 0.3) This library has even more tricks up its sleeve. If you want to fade that LED up and down instead of just blinking, that last line could say led.blink(on_time = 2.0, off_time = 2.0, fade_in_time = 1.0, fade_out_time = 1.0 ) This is great if you only want to do that, and for a very young beginner, that’s exactly what you want to do. The blinking speed controlled by a push button can be written like this. #!/usr/bin/python3 import time, os import gpiozero as io # using GPIO Zero led = io.LED(4) # make pin 4 into an output push = io.Button(24) # make pin 24 into an input print("LED blinker switch using gpiozero - By Mike Cook") print("Ctrl C to quit") while True: led.on() if push.is_pressed: time.sleep(0.30) else : time.sleep(1.00) led.off() if push.is_pressed: time.sleep(0.30) else : time.sleep(1.00) The input works in a similar way to the output. In this case, you make an instance of the Button class and put its reference in the variable push. Then you use the is_pressed method of this class to determine the time delay in the blinking. By default, the input pull-up resistor is enabled when you create the class reference. There are other options contained in this input class. It can specify whether a press is to be auto-repeated or specify a debounce time — the time after a change to ignore further changes. As well as the is.pressed method, other class methods include is_held, wait_for_press, wait_for_release, is_held, when_held, when_pressed, and when_released. Rather than return any information about the input, these last two cause a function to run when the button is pressed or released. This other function runs in a separate thread — in effect, another separate program — with this thread and the main code being swapped in and out alternately until the function is complete. This gives a beginner access to complex concepts that they need to understand only when something goes wrong. So, our controlled blink-rate program could be written as shown. #!/usr/bin/python3 import gpiozero as io # using LED zero from signal import pause led = io.LED(4) # make pin 4 into an output push = io.Button(24) # make pin 24 into an input def blinkFast(): led.blink(on_time = 0.3, off_time = 0.3) def blinkSlow(): led.blink(on_time = 1.0, off_time = 1.0) push.when_pressed = blinkFast push.when_released = blinkSlow pause() The pause function, in effect, ends the program, and the only thing that happens is when the callback functions, as they are called, are invoked or triggered on the push or release of the button. A lot of the programming work involved in using GIPO Zero involves leafing through the documentation to see what simple functions the authors have implemented for you. GPIO Zero enables you to get results quickly, and without needing to understand much of what is going on — which is helpful if a function does what you need. However, although some things can be done simply, the skills learned are not exactly transferable. As you develop more complex electronic projects, you might find GPIO Zero to be too limited for your needs.
View ArticleArticle / Updated 11-07-2017
Sonic Pi enables you to use proper note names instead of MIDI numbers to play music on the RaspberryPi by using the name of the note (a letter from A to G), plus the number of the octave it’s in. For example, to play a middle C, you can use play :c4 To play the B one note before it, which is in the next lowest octave, you would use play :b3 The Log shows that Sonic Pi plays notes 60 and 59 respectively. You can check the note names and numbers to confirm that this is what you expected. MIDI Notes Note 0 1 2 3 4 5 6 7 8 9 C 0 12 24 36 48 60 72 84 96 108 120 C# 1 13 25 37 49 61 73 85 97 109 121 D 2 14 26 38 50 62 74 86 98 110 122 D# 3 15 27 39 51 63 75 87 99 111 123 E 4 16 28 40 52 64 76 88 100 112 124 F 5 17 29 41 53 65 77 89 101 113 125 F# 6 18 30 42 54 66 78 90 102 114 126 G 7 19 31 43 55 67 79 91 103 115 127 G# 8 20 32 44 56 68 80 92 104 116 A 9 21 33 45 57 69 81 93 105 117 A# 10 22 34 46 58 70 82 94 106 118 B 11 23 35 47 59 71 83 95 107 119 Here's how you could code a fanfare using note names instead of numbers: play :c4 sleep 0.5 play :e4 sleep 0.5 play :g4 sleep 0.5 play :c5 If you want to use a sharp note, insert the letter s in the note name (for example, play :cs4) and use b for a flat note (play :cb4). You can also use names to play chords. You tell Sonic Pi the lowest note in the chord and add which type of chord you want (try :major, :minor, or :diminished). There are also options for :major7, :minor7, :diminished7, and :dom7, among others. For a complete list, click Lang in the Help pane, and then select Chord. Try this: play chord(:a3, :major) sleep 1 play chord(:a3, :minor) In each case, it plays three notes at the same time. If you look at the note numbers in the Log, you can see that the middle note was one pitch lower in the second chord because it’s a minor chord. Again, you can use Table 14-1 to check the note numbers Sonic Pi displays against the musical note names. The chord is returned as a list, and you can use play_pattern to hear the notes of the chord in a sequence, like this: play_pattern chord(:a3, :major) play_pattern chord(:a3, :minor)
View ArticleArticle / Updated 11-07-2017
Let’s do some fun stuff with your Raspberry Pi’s LEDs: mixing colors. Yes, you can turn on just one LED at a time, and that will give you one of the three colors — red, blue, or green. However, turn two on and the colors will mix in a way known as additive mixing. The primary colors are red, green, and blue. Mixing them together gives you other colors, the so-called secondary colors. So a red-and-green light together make a yellow one. A green-and-blue light make a cyan color, and a red-and-blue light make magenta. Turn on all three LEDs together and you make white — or, more precisely, they make a white tint. In theory, all three LEDs on together will make white, but in practice this depends on the exact brightness of the three separate lights. They have to be identical to make a pure white; otherwise, the white looks tinted, which is not altogether a bad thing. It's not an easy task to do this, because each color has a different forward voltage drop — you need different resistors to ensure the same current through each LED. Not only that, each color of LED converts current to brightness with a different efficiency, which complicates things tremendously. You might be used to mixing colored paint, but keep in mind you get different results doing this than mixing light. Paint mixing is known as subtractive mixing because each paint color you put into the mix takes out (or subtracts) some other color. This is how your color printer works. For subtractive mixing, the primary colors are cyan, magenta, and yellow; red, green, and blue being the secondary colors. Using diffusers The light from three LEDs in the same package will still be seen as three separate points of light, unless there is some sort of diffuser, which allows the light to mix evenly. For individual RGB LEDs, this is sometimes provided by the package or body of the LED itself. Viewing distance alone can provide enough diffusion to mix the colors, but often a diffuser of some sort will help. Diffusers also reduce the brightness per unit area of the LED, making it much easer to take a good color picture. You can use anything that is translucent as a diffuser. Our favorite is a very thin styrene sheet — about 0.5mm thickness is fine and is easy to work with, because it can be cut with scissors. (A good alternative is a simple sheet of paper.) If you have several LEDs and want to see the light from each distinctly, then you have to have each one surrounded by a light baffle — sometimes known loosely as an egg box, or waffle box. Without the baffle, the light from each LED mixes with those adjacent to it and gives a soft focus effect that is not at all unpleasant. The degree of diffusion you get is proportional to not only the diffusing material but also the distance of that material from the LED. In most cases, a few millimeters is fine. You can turn the clear-plastic housing LED into a diffuser by rubbing it gently with very fine sandpaper or wire wool. Even better is to use a foam-backed sanding block, because it gets round the curves much better than paper. These LED housings are made of resin, so solvents like acetone do not affect the surface. Making more colors on your Raspberry Pi The trick to making more colors than the simple primary and secondary colors is to have different brightness of each of the three colors. In that way, many more subtle colors can be made. So how can you control the brightness of an LED? Well, the answer might not be immediately apparent, but what you need to do is to turn the LED on and off very rapidly. If you do this fast enough — that is, faster than about 30 times a second — then the eye/brain sees this as a light that is constantly on and not flickering. Furthermore, you perceive the brightness of the LED according to the relative length of the On and Off times. That is, if the LED is on and off for equal times, the LED appears to be only half as bright. This rapid switching technique is known as PWM — short for Pulse-Width Modulation — and is the way you control the LED's brightness. The waveforms are shown here. You can see that the three PWM signals go on an off at the same speed; however, the one that spends more time being on is brighter than the one that spends only half the time being on. Finally, the last waveform has a little time on but a long time off and produces a dim LED. The ratio of the On time to the Off time is known as the duty cycle of the waveform. Note that the frequency of this PWM signal does not matter once it is above the rate where you see it flicker. The RPi.GPIO library has the ability to make the GPIO pins output a PWM signal, and the library can set both the frequency and duty cycle. If you wire up an RGB LED according to the image above, you can test out the colors an RGB LED can produce with this code. #!/usr/bin/python3 import time import RPi.GPIO as io io.setmode(io.BCM) io.setup(17,io.OUT) # make pins into an output io.setup(27,io.OUT) io.setup(22,io.OUT) ledR = io.PWM(17,60) # Set up outputs as PWM @ 60Hz ledG = io.PWM(27,60) ledB = io.PWM(22,60) ledR.start(0) # start off the PWM ledG.start(0) ledB.start(0) print("RGB color cycle an LED using RPi.GPIO - By Mike Cook") print("Ctrl C to quit") try: while(1): print("Start cycle") time.sleep(2.0) for stepR in range(0,100,5): for stepG in range(0,100,5): for stepB in range(0,100,5): ledR.ChangeDutyCycle(stepR) ledG.ChangeDutyCycle(stepG) ledB.ChangeDutyCycle(stepB) time.sleep(0.1) # Whole cycle 8000 times this ledR.ChangeDutyCycle(0) ledG.ChangeDutyCycle(0) ledB.ChangeDutyCycle(0) except KeyboardInterrupt: pass ledR.stop(0) #stop the PWM ledG.stop(0) ledB.stop(0) io.cleanup() # Restore default GPIO state When you walk through this listing, you see that the first thing the code does is set three GPIO pins to be outputs and then set them up to produce a PWM signal. The value 60 in these opening lines of code is the frequency 60 Hz, which is the frequency the PWM signal will go at. The duty cycle goes from 0, which is off all the time, to 100, which is on all the time. The main part of the program consists of three nested for loops, which ensure that all combinations of red, green, and blue are produced in duty cycle steps of five. It takes 800 seconds — just over 13 minutes — to do a complete cycle where 8,000 colors are produced. It might not look like that many colors when you test your LED output running this code, but they are all there. It’s just that many of them from this demonstration might look the same. This has to do with the way people perceive colors — they’re much more sensitive to the difference between two colors than to the colors themselves.
View ArticleArticle / Updated 11-07-2017
There are basically two types of ready-made boards for the Raspberry Pi: those designed for making it easy to get access to the GPIO pins and those with components that have already been soldered up. Since the introduction of the Raspberry Pi in 2012, many companies have produced ready-made boards with all sorts of components already built on. They normally come with sample code to show you how to use them, and many users just stick to that. However, this can be a wasted opportunity because you can always do more with a board than is shown in these examples. Many of these boards contain sensors that allow your Pi programs to measure things. New boards are constantly being developed and produced. Boards come in three styles: Separate boards that connect to the GPIO pins via a ribbon cable or your own wires. Boards that plug into all the GPIO pins and cover most of the area of the Raspberry Pi board. These are sometimes called shields or plates. Boards similar to the shield/plate variety just mentioned but contain in addition an identification and sometimes software so that the Pi can read what they are on start-up and install some software and prepare the GPIO pins automatically. These are called HATs — short for Hardware Attached on Top. The Sense HAT The Sense HAT was specifically designed for the Astro-Pi mission and two ruggedised versions were flown on the International Space Station from December 2015 running code written by school children. It has an 8×8 RGB LED matrix, a 5-button joystick, and sensors to measure acceleration, magnetism, temperature, pressure, and humidity — as well as a gyroscope. The Sense HAT also has an extensive Python library associated with it, which allows for easy access to this board. You can find comprehensive coverage of how to use the Sense HAT on the Raspberry Pi Foundation's website. The Skywriter HAT The Skywriter HAT is an electric near-field 3D proximity sensor. With it, you can make gestures with your hands waving above it, which can then be detected by the library software, causing your own functions to run. Gestures such as flicks right, left, up, and down can easily be detected along with a circular motion of the finger. It also detects taps made directly to the HAT surface. It has a range of about 5 centimeters and can be mounted behind any nonconducting surface, such as an acrylic sheet. The Xtrinsic Sense board The Xtrinsic Sense board is a low-cost sensor board, in some ways similar to the Sensor HAT but without the LEDs. It is made in partnership with the component distributor and Raspberry Pi co-manufacturer Farnell. It contains a high-precision pressure sensor in the range 50 to 110kPa, a 3-axis, digital accelerometer, and a 3D magnetometer. As you can see, it sits over less than half the Raspberry Pi and can be used, among other things, with robots and high-altitude balloons. Other boards There are many other boards available from small start-up manufacturers as well as web-based projects for you to build. Here’s a good starting point for information on expansion boards.
View Article