Mastering Raspberry Pi 4 Projects in 1 Hour
Mastering Raspberry Pi 4 Projects in 1 Hour
RASBERRY PI 4
PROJECTS
IN 1 HOUR
A Simple Guide to Program, Develop and Setup Unique Projects on
Raspberry Pi 4
Colin Schmitt
Copyright
All rights reserved. No part of this book may be reproduced or used in any manner without the prior
written permission of the copyright owner, except for the use of brief quotations in a book review.
While the advice and information in this book are believed to be true and accurate at the date of
publication, neither the authors nor the editors nor the publisher can accept any legal responsibility for
any errors or omissions that may be made. The publisher makes no warranty, express or implied, with
respect to the material contained herein.
Printed on acid-free paper.
CHAPTER THREE
Using your Raspberry Pi 4
I tpurchasing
has been on your mind for a while now, you’ve always thought of
it, and now you’re the owner of a Raspberry Pi 4 board! But
what can you use it for, don’t worry too much, I’ll also help you with that.
The functions that will be mentioned are mainly for the Raspberry Pi 4,
nevertheless, most of these functions are also applicable on the Pi boards, the
Raspberry Pi zero inclusive.
-You can use the Raspberry Pi 4 in place of a PC.
This is probably the simplest use of the Raspberry Pi 4. Asides the Pi 4 board
itself, there’s the microSD card, screen (monitor/ TV), USB mouse, USB
keyboard, power supply, Wi-Fi, Ethernet ports. All these peripherals
combined and set up with the Raspberry Pi 4 gives a replica of a desktop
computer with little or no difference in terms of function and output. Also,
after setting up the device and starting it, you’ll find the chrome browser and
Libreoffice because they have been pre-installed on it.
/home/pi/mystuff/and_so_on…
Document addresses are likewise referred to as Paths. Reaching an address is
somewhat similar to strolling down a path with numerous turnings
To pinpoint a record at that address:
- Click the/home folder
- Click the/pi folder inside home.
- Continue opening folders to glimpse inside them until you reach your
desired folder. As you keep on opening an ever-increasing number of
folders, file Manager consistently informs you about your location in
the folder, so It’s difficult to get lost.
Here’s a genuine model, which takes you to the pre-introduced applications
in your Pi:
/usr/share/raspi-ui-supersedes/applications
Check whether you can keep on clicking till you locate the documents. You’ll
have to move down the tree to have access to all the folders in/usr/share, on
the grounds that there’s a great deal of stuff in there. The accompanying
figure informs you about all the applications in File Manager. The envelope
incorporates the applications in the desktop menu and so much more. You
can double-click on any of these items to open it.
• 1-Wire
Enabling the 1-wire interface is important if you’re planning to use
something like the DS18B20 temperature sensor or other devices that make
use of the 1-wire protocol.
• Remote GPIO
With this option, you will obtain remote access to the GPIO pins and should
only be activated if it actually needs to be used.
• Overclock
When you overclock your Raspberry Pi, you harness more power out of it.
By default, the Raspberry Pi overclock settings is deactivated, and the CPU is
placed at 700 MHz However, you can decide to overclock it up to 1000 MHz
with the aid of this feature. These values will differ contingent upon the
version of Raspberry Pi you have. You should also bear in mind that
overclocking might lead to higher instability and mitigate the lifespan of your
Pi. It is also deactivated on later versions of the Raspberry Pi, such as the
Raspberry Pi 3.
• Advanced Options
These options look like the final lot of choices in the Raspberry Pi
Configuration tool and they’re relatively more complex. You don't have to
manipulate these options unless what you’re doing exceeds the basics of the
Raspberry Pi.
• Expand File system
You can ignore this option if you’ve earlier installed the Raspbian operating
system through New-Out-Of-Box Software (NOOBS), this is because
NOOBS itself expands the file system for its users. However, if you brought
in the Raspbian image directly into the Raspberry Pi through an image rather
than NOOBS, then your access will be restricted to only the first 3GB of the
SD Card.
You can utilize this option to boost to full SD card capacity, not 3 GB alone.
This expansion will enable you to put more stuff onto the SD card, however,
you have to reboot after activating this option.
• Overscan
If it happens that your TV has a black border at the sides, then it’s most likely
due to the problem of Underscan. On the other hand, if the stuff happens to
be flowing off the screen, the issue is Overscanning. If the issue you’re
battling with is Underscan, you should activate this overscan option, it will
help in fixing the screen. This can be edited more in the config.txt to achieve
this so that images are displayed correctly on your monitor/TV.
• Memory Split
The memory split option permits you to adjust the capacity of the memory
that is made accessible to the Graphics Processing Unit. You may need to
enlarge or reduce this depending on what you want to do with the Pi.
• Audio
The audio option allows you to compel sound out of either the 3.5mm jack or
the HDMI port. Basically, this option has been set to auto, which implies that
it will automatically determine which output to send sound through.
• Resolution
In case you’re not satisfied with the default resolution, then you can change it
with this option. As the Raspberry Pi becomes more powerful, there is a
likelihood that more resolution choices would be available to pick, so it’s
certain you will need to check this option later.
• Pixel Doubling
The pixel doubling option replicates every pixel on the screen by doubling it,
therefore making the entire item twice as large. This option is handy on high-
resolution screens or large screen TVs. Furthermore, it is a useful option for
people who have visual impairments.
• GL Driver
Simply enables you to activate or deactivate the experimental GL driver. It’s
best to deactivate this option unless you’re certain that you’ll need it.
- Update
This option, as its name implies, will update the Raspberry Pi Configuration
tool and other software applications to the most recent version. This tool is
constantly being updated, therefore it is crucial to keep it updated.
- About Raspi Config
This option elucidates more about the Raspberry Pi Configuration tool if you
intend to know more information.
- Removed Features
In case you’re looking for other features, you can stroll down to locate them
- Add to Rastrack
You will find this option useful if you want your Raspberry Pi to be added to
the global map of Raspberry Pi users around the globe, that is when you will
use this option to have your Pi added.
- Finish up with the Raspi Config Tool
Click Finish when you’re satisfied with the changes you have made. You
might be inquired as to whether you might want the Raspberry Pi to reboot, it
is typically best to permit it to reboot so all the changes made can be applied.
However, if you change the size of your SD Card during the configuration,
you might experience a delay during the rebooting process.
CHAPTER FOUR
Introduction to Scratch Programming
S cratch is a visual programming application that permits users to create
animations and games via a drag and drop framework. This application
enables you to build your own computer games, animations and
interactive stories with the aid of basic programming skills without the
essential need of having to write code. Scratch is a superb way to get young
people to start programming on the Raspberry Pi. Even though scratch was
developed for people who are newbies to programming, nevertheless, even
experts might still find it a bit difficult at certain points; let's talk about the
concepts of Scratch.
Projects
Projects are those items or anything that are built with scratch; they include
stories, arts, animations, games, pen etc. Projects in scratch are made with a
scratch project editor, and these projects can be shared globally with the aid
of the Scratch Community. In other words, a project is a developed coding in
scratch.
A scratch project
• Offline Editor vs Online Editor
Scratch provides its users with two varieties of editors. There's an online
editor and an offline editor. Although these two editors look alike, there are
slight differences between them. You can access the online editor clicking the
"Create Tab" option on the website. The offline editor on the other hand, can
be downloaded.
• The Interface
The users' Interface for the scratch programming application is divided into
two aspects, which are: the project overseeing the environment and the
project development. At the crest-corner of the Scratch screen, you'll find the
Stage, it is displayed just above the image. Typically, the Stage is the
platform in which scratch projects are carried out. Therefore, when one plays
a game, the stage is the window in which it runs. As a default setting, the
scratch cat is what you'll find in the Scratch Stage. This Scratch cat also
happens to be among the numerous sprites or entities, buttons etc. in a scratch
project. These entities or characters have been instructed to carry out what the
Scratcher instructs them. The flexibility of Scratch enables the user to bring
imaginative thoughts into reality and actually achieve the intended, and it is
at this point that programming plays a role, as it enables the entities to carry
out their functions.
• Programming
Prior to getting deep into the work-area, the most easy and useful way to
perfectly comprehend how Sprites or entities are programmed in Scratch is
by trying things out yourself. Here are some steps to put you through this
task:
- Open the area displayed below in the Scratch program.
- Pick the blue "block" tagged move () steps and drag it towards the right
portion of the screen.
- Let go of the mouse so that you can position the block, ensure that the
block is placed in the darker grey area, which is referred to as the Scripts
area.
- After doing that, click on any spot on the block asides the white middle and
observe the effects it has on the scratch cat, it moves by exactly 10 steps.
- Check the other block categories and try them out to know what each option
does.
• Blocks
Just as its name implies, blocks are the basic units of any project on Scratch.
They are embedded with specific commands that carry out unique tasks; a
number of blocks can be put inside other blocks.
- Gather these "script" or linkage of blocks, by looking into various blocks
based on their color and their category.
- Press the displayed Green Flag to put the project into action and observe its
effects.
- You may be surprised that nothing happened, that's totally expected. The
reason is you were not pressing the space key after pressing the Green Flag.
If you don't hold down the space key when you want to run the scratch codes,
there'll be no changes. Let me make that more detailed, the script starts with
"When green flag clicked" which you have done. Clicking the Green Flag
sets the script into motion starting with making the "When green flag clicked"
block to run. When the script runs, it first notices "if the space key is pressed
down," if the space key is pressed down, then the Sprite will move by 10
steps. Now that you're clear, run the program, and this time, hold the space
key down and watch the Sprite move.
• Paint/ Sound editors
Scratch, of course, has a unique paint and sound editor. A paint editor can be
said to be a program that is used to design and edit images. The paint editor
in Scratch can be utilized to draw images for sprites. While the sound editor
is a program that can be used to record, import or modify sounds used in a
project. To display these editors, click on the tabs directly above the block
palettes.
• Sprites
Sprites are best described as the characters of a particular Scratch project.
Each Sprite has its unique blocks and they can interact with one another using
Broadcasts. Also, each Sprite is capable of carrying out its functions, for
instance, in a game whereby a dog is supposed to chase the Scratch cat, the
dog has been instructed to chase the cat while the Scratch cat is being
directed by the player. You'll observe that these two sprites have been
programmed to carry different functions, in the same way, a program can
contain over 50 sprites, each carrying out its function.
• Sprite Pane
Gaining access to different sprites can be done via the sprites panes, which
are situated beneath the stage. A blue box will surround the sprite that you've
currently selected. When you click any sprite, its details will be displayed.
• Creating New Sprites
Nearly all the projects on the Scratch application require two or more sprites.
At the bottom-corner of the sprite panes, there is a button that enables you to
create new sprites. Pressing this button provides you with some options. You
can bring in a new sprite with this option, either in the form of an image or as
an entity, which initially has a script. The buttons go thus according to the
image;
- Picking a sprite from the sprite library.
- Opening the paint editor to draw a sprite.
- Getting a random sprite.
- Bringing in an image from the computer via Scratch.
• Backdrops
Another important feature of a work is its background; backdrops are not
motile but can be employed to do certain things such as playing music,
sending a broadcast and other functions. In a similar manner to sprites, they
have pictures that can be edited as well with the aid of a paint editor. Beneath
the backdrops, there's a button whose function is to bring in a new backdrop.
• Project Sharing
This provides you with more options on how you can share projects.
• Sprites Pane
The sprites pane entails a thumbnail view of the entire sprites.
- It entails the names of the sprites bearing a thumbnail of the sprites present
costume near it.
- If you're active on the Sprites Pane, the thumbnail will change gradually to
avoid annoyance. Nevertheless, if it's opened into the sprites information
pane, it will transform at the present rate.
- You can include a new sprite by selecting any of these:
- Giga: This launches the window with Scratch Default Sprites.
- Paint Brush: Opens the paint editor. A new sprite will originate from what
you paint.
- Folder: This opens the file browser, therefore enabling you to open a sprite
or image file.
- Camera: Launches the camera and snaps a picture when you instruct it to.
- When you click on a sprite, it opens up either the Script Area or the
Costume Pane.
- If you want to bring in a costume, you drag it to a different sprite and the
costume will be inserted into that sprite's Costume Pane.
- Moving audio to a different sprite will duplicate the sound into that sprite's
Sounds Pane.
- Moving a sprite onto another sprite will switch their positions in the sprite
pane.
- Right Clicking a sprite provides you with a rundown containing four
options:
- Duplicate: Produces a similar version of a sprite including costumes,
scripts and sounds.
- Delete: Erases the sprite.
- Save to local file: Opens up a file browser that enables you to save your
sprite together with any script in the selected sprite.
- Show: Displays the object in case it's concealed and sends it to the front.
- Moving a script from the thumbnail of one Sprite to the thumbnail image of
another will copy the scripts to that sprite.
• Sprites Info Pane
The sprites info pane contains information regarding the sprites that have
been selected and some tools for making adjustments on the Sprites. This
pane is displayed when you click the blue (i) in the Sprites Pane.
- You can change a sprite's name by clicking the box that has the sprite's
name in it.
- Some adjustments can be made to the sprite's name by pressing any of these
buttons:
- Can Drag In Player: Selecting this option will make the sprite draggable
outside the editor.
- Circular Arrow — This permits full rotation of a sprite.
- Linear Arrow — Allows the sprite to face the left or right direction.
- A large dot: This disables the rotating feature of the sprite; it will keep on
facing 90 degrees no regardless.
- Pressing and moving the blue line positioned over the sprite will cause the
sprite to rotate.
- Double-clicking the sprite will return its orientation to 90 degrees.
- The sprite's X and Y coordinates and the directions are stated.
• Costume Pane
The costume pane bears the list of costumes of the sprites that have been
selected
- It entails the name of the sprite as well as a preview image.
- When you click on a frame, the sprite transforms into that costume
- You can include new costumes via any of these options:
- Giga: This opens the scratch's embedded library on sprite and enables you
to choose any costume.
- Paint: Brings in the paint editor
- Import: This opens the file browser, thereby permitting you to open a sprite
file.
- Camera: This launches the webcam or external device to take a picture that
will be used for a new costume.
- Adjustments can be made to costumes in the paint editor positioned at the
right side of the screen
- You can rename a costume by clicking the box that bears the costume name.
- When you right-click on a costume, it provides you with a rundown of three
options, these are:
- Duplicate: This makes a replica of the costume.
- Delete: This option erases the costume
- Save to local file: Saves the costume to whichever location you choose.
- You can rearrange costumes by moving them into the correct email order on
the list.
• Sounds Pane
This pane entails a list of audio clips.
- The sound pane contains the title of the sounds, and the thumbnail of a
speaker
- The sound will be played when you click the speaker icon.
- You may include a new sound to the list when you press any of these
options:
- Record: This opens the sound recorder, and by so doing, you can record
audio from an external device.
- Import: This opens the file browser, thereby enabling you to bring in an
audio file.
- A sound can be played by clicking on the play button positioned near the
speaker icon.
- A sound that is currently being played can be put to a halt when you press
the stop icon, which is also located near the speaker icon.
- You can remove a sound by clicking the "X" button
- You can rename the sound by clicking the box that has the name listed in it.
- When you right-click a sound icon, it provides you with the following
options:
- Duplicate: This makes a replica of the costume.
- Delete: This option erases the costume
- Save to local file: Saves the costume to whichever location you choose.
• Stage
The stage can be said to be a sprite that functions as the background of the
project. Due to these functions, it has traits that are unique relative to other
sprites. No sprite is enabled to move behind the stage, the stage will always
be found at the background and likewise, it cannot move itself. There are two
buttons you can find here, they are:
- Green Flag: This interacts with the "When Green Flag Clicked" block
- Stop: This halts the entire scripts in all sprites.
- You can move sprites to the stage by dragging them.
- The entire actions take place in the stage
• Toolbar
You will find the toolbar at the topmost section of the program, and it
performs numerous functions in scratch. On the crest corner, you'll see the
text "Scratch." Next to this text, you'll see the picture of a grey sphere, if you
press this image, it provides you with a rundown of all the languages
available in Scratch. Following this grey image, you'll find several options
here.
- File menu: when you click this, it also provides you with various options
> New - This creates a new project from an empty template.
>Save now - This option saves the present project in the directory from the
directory that it originated from. In case the file is new, it opens a file
browser, which helps you to save the project as a new file, excluding when
you're online.
>Save as copy - This creates a duplicate of the present project.
>Go to My Stuff — This button directs users to their My Stuff page.
>Upload from your computer — Opens a file browser, and by so doing, it
opens a project. Opening this project this way prevents the sprites from
appearing in the program you were previously working on.
>Download to your computer — This opens a file browser, inquiring the
intended location for a current project to be saved.
>Revert — Transforms the project to the state it was during a previous save.
- Edit Menu
> Undelete: This reverses a recent delete command on a sprite, costume,
sound, or script.
>Small Stage layout: Reduces the size of the stage
>Turbo mode: This sets the player into turbo mode. In turbo mode, codes
are executed quickly.
- Tools
>Duplicate: This button, which is indicated by a stamp icon, makes a replica
of anything that is displayed. It makes a duplicate of sprites, costumes,
costume selections, sounds, blocks, and scripts
>Delete: The delete button is indicated by a scissors icon and its function is
to delete anything that's on the screen. The delete button deletes sprites,
costumes, costume selections, sounds, blocks, and scripts. There are also
other options such as enlarge and shrink, which function when you click on a
sprite in the stage, costume editor, or any selection at all in the costume editor
will make the sprite or selection grow bigger or become smaller respectively.
CHAPTER FIVE
Project 1: Astronaut Reaction Timer
• Introduction
In this first project, your aim will be to make use of Scratch to develop a
game that will test how fast your reaction is and analyze the distance
travelled by International Space Station in the duration it takes you to react.
Press the Green Flag to begin the game. Press the spacebar on your keyboard
when you head the word “Go!”
• Get Started
The next task is to convert the “Hello!” command to a different greeting. You
can employ this write up below or come up with anything that suits you.
Afterwards, include a “wait 1 seconds” block and input some codes that will
inform the players what to do next, whether they need to keep on waiting
while it loads, or they should press any key or a particular key on the
keyboard.
Now, press the Green Flag to test your game and ascertain whether it works.
• Include a random pause command
The game should start just immediately, and the beginning should be one that
cannot be predicted by the players. Include a couple of blocks into your
program to ensure it holds on for some seconds before it starts to run, and
then make the sprite say “ Go!”. The blocks you’ll include to perform this
might be hints about how to make certain movements or techniques in the
game.
• Calculate Reaction times
To work out the reaction time of the player, you can use Scratch’s
programmed timer. Include a “Reset Timer” block to your script.
The timer will then start to count from zero seconds. The timer has to halt
when the player presses the spacebar. Input the “Wait Until” block and a
“key spaced pressed?” block to initiate the next aspect of the program.
Then, inform the players how much time it took them to press the spacebar.
Utilize “Join” blocks to state the number of seconds it took them.
• Analyze Distances
Now that the program is aware of the reaction time of the player, develop
some codes to determine the distance International Space Station would have
travelled in that duration.
- Bring in a new variable called Kilometres. Bearing in mind that ISS travels
at about 7.66 kilometres per second
- Include blocks to your code so that the variable you’ve Just added
(Kilometres) is tagged with the distance ISS would have covered.
• Finish the game
Here, the astronaut sprite has to inform the players of the distance they would
have travelled on the ISS. To ensure your calculations are much easier to
read, you can utilize a “Round” block. This will round up and approximate
the number to become a whole number. Input it by using “Say”, “Join”, and
“Join” blocks to inform the players of the values of “Kilometres” Variable.
Well done! Now you can move on, try out other projects of your choice, and
see what the outcomes are.
CHAPTER SIX
Project 2: Synchronised Swimming
• Introduction
This project will give you knowledge about how to program a synchronized
swimming routine for Scratch cat with the aid of loops and creating replicas.
• Swimming left and right
In this project, a team of swimmers will be programmed to perform a
rhythmical style of moves to a music. First, let’s get one cat swimming.
Launch a new Scratch project. If you prefer the online version, open a new
online Scratch project. If, on the other hand, you will go with the offline
mode, then open a new project in the offline editor. Perhaps you prefer the
Scratch offline editor, click on this link: rpf.io/scratchoff.
Now, transform the stage so that it resembles a swimming pool. You do this
by clicking on the “Stage”, then select “Backdrops” tab and press “Convert to
Bitmap”
Choose a blue color
and the “Fill with color” tool, after doing that, click the backdrop.
Verify your code by pressing the left and right arrow keys on your keyboard
and see if the position of the cat changes. That being settled input additional
codes for the forward and backward movement of the cat.
Now, put your codes into action by swimming around the stage utilizing the
arrow keys.
•Costume
You can as well change the costume of the Flying cat to any one you desire.
Simply click on “Costumes” and erase the “Cat Flying-a” costume. Change
the name of the other costumes from “Cat Flying-b” to “Right”. After that,
you right click on the costume and press “Duplicate” so that it creates a
replica.
At this juncture, click” Flip Horizontal” to revert the copy, then you name it “
left” and you should be left with something similar to this:
Press “Code“ to revert your code and include blocks to alter the costume
whenever the direction is changed.
It is important that you run the game at this juncture so you can be sure that
the arrow stops moving whenever you press the spacebar.
Now, the next thing to do is to
animate your arrow to make it resemble an object moving towards its target.
CHAPTER EIGHT
Using Python Programming Language on Raspberry Pi 4
Web Download
The web download can be gotten to through an internet browser by visiting
the Thonny site. Once on the page, a dim light box will be displayed at the
upper right corner. When you've seen the dim box, click the suitable link for
your Operating System.
The Icons
Over the top, you'll see a number of icons. You'll see a picture of the symbols
beneath, with a letter over every one. These letters will stand in for each of
these icons.
application window:
Thonny's "View" Dropdown
Let's also go into what these options have to offer.
- Help: You'll select the Help view in case you need more information about
working with Thonny. Presently this segment offers more information on the
subjects such as Running Programs Step-wise, how to introduce outsider
Packages, or utilizing Scientific Python Packages.
- Variables: This element can be entirely important. A variable in Python is
valuable that you characterize in code. Variables include numbers, strings, or
other complex data structures. This segment permits you to see the qualities
doled out to the entirety of the variables in your program.
- Assistant: The Assistant is there to give you accommodating insights when
you hit Exceptions or different sorts of mistakes.
Different features will get helpful as you advance your skill. You should
check them once you become more conversant with Thonny!
So
as to run your code, find and press the play icon. The result should be like
this:
• Debug Your Code
To genuinely comprehend what this feature is doing, try the step feature.
Take just a few large and little steps through the function to observe what's
going on. Recollect you can use the arrow icons to do this.
Judging by the image, you will see that the steps will show how the PC is
assessing each piece of the code. Each pop-up window resembles a little part
of scratch paper that the computer is using to evaluate each section of the
code. Without this wonderful element, this may have been difficult to
conceptualize.
.
CHAPTER NINE
Turtle Snowflake
• Introduction
This project aims at creating beautiful snowflakes with Python Turtle on the
Raspberry Pi. This is absolutely interesting and an efficient way to learn how
to code with Python.
• How to draw with the Python Turtle
Launch the blank python template trinket and input these letters into the
window that will be displayed.
The line #!/bin/python3 just informs your computer that you’re using
python 3, which is the most recent version of Python. To start using Turtle in
Python, you need to bring in the Turtle library. At the crest of the text editor
window, input “Import Turtle.” Now, give your Turtle a title, you can utilize
a variable to do this. Let’s call this Elsa.
● Elsa = turtle.Turtle()
Hence, you can instruct your turtle on what it should do, for instance, if you
want it to forward (100)
● Elsa.forward(100)
Now, click on run to test your turtle program and observes what happens
You should bear in mind that a trinket account might not be necessary if you
want to save your projects. You can simply click the downward-facing arrow
and then press Link, if you don't have a trinket account. This will display a
link that you can save and revert to later. However, you will need to do this
each time you make any adjustments to your code, the reason being that the
link will also change as you make changes to the code. And if you have
already registered a trinket account, click Remix to save a duplicate of the
trinket.
To
even make it more artistic, you can include random colours for your Turtle to
ensure that each time you run your code, you’ll be provided with a somewhat
different snowflake.
To start with, you have to import the “random” library, below the “import
turtle,” input “import random.” The next task is to change the background
color from “blue” to “grey”. Just beneath that line, create a Variable called
“colors” to store a list of the colors you’ll choose from.
Colours = [“cyan”, “purple”, “white”, “blue”]
At the end of the spiral loop, below elsa.right(36), input this:
Elsa.color(random.choice(colours))
Also, ensure that you indent this line so that your program stays aware that
it’s within the loop. Go ahead and save the codes, then run it and see a
multicolored snowflake!
Include a #
at the start of the “elsa.color(random.choice(colours)) instruction to
change it into a comment. This implies that the computer will ignore that
particular line of code. If you like, you can delete that line, however, it might
be useful in case you want to include colours to your snowflake at a later
time. As usual, save the code, and run it, a snowflake should appear on your
screen.
CHAPTER TEN
Physical Computing with the Raspberry Pi
Physical computing with Python: Introduction to GPIO header
Here, you will learn how to use GPIO pins on your Raspberry Pi to connect
with electronic gadgets such as Light Emitting Diodes (LEDs) and Passive
InfraRed Sensors (PIRS). One amazing element of the Raspberry Pi is the
line of GPIO pins along the top edge of the board. GPIO represents General-
Purpose Input/Output. These pins serve as links between the Raspberry Pi
and the outside world. At the least difficult level, you can consider them
switches that you can activate or deactivate (input) or that the Pi can turn on
or off (output). The GPIO pins permit the Raspberry Pi to control and
monitor the external world by being associated with electronic circuits. The
Pi can control LEDs, turning them on or off, run motors, and numerous other
things. It can also detect when a switch is pressed, the temperature, and light.
We allude to this as physical registering. There are 40 pins on the Raspberry
Pi (26 pins on early designs), and they offer several functions
The LED is expected to turn off now, however it’s now on a GPIO pin, and
can hence be directed by code.
Up until now,
you can control output components with which is a Light Emitting Diode,
now let’s make an attempt to connect and control input components,
specifically, a button. To do this, connect the button to another GND pin and
GPIO pin 2, just as it is shown in the image below:
Bring in another file by clicking “New”
- Store the file by clicking on “Save”. Save the file as gpio_button.py.
When you get to this stage, you’ll need the “ Button” class and instruct
it that the button is on Pin 2, input these codes into your new file:
From gpiozero import Button
Button = Button(2)
Now you can get your program to carry out something when you press the
button. Add these lines:
Button.wait_for_press()
Print(‘You pushed me’)
Save and run the code.
Press the button, and your text will appear
As usual, save and run the program, the LED should be displayed for about
three seconds when you when the button is pressed.
Making a Switch
When you employ a switch, pressing and releasing the button just once would
switch on the LED, pressing it again would then switch it off. Adjust your
codes to something like this:
From gpiozero import LED, Button
From time import sleep
Led = LED(17)
Button = Button(2)
While True:
Button.wait_for_press()
Led.toggle()
Sleep(0.5)
“Led.toggle” switches the state from on to off, or vice versa. Since this
occurs in a loop, the LED will turn on and off each time you press the button.
It would be more preferable if you could set the LED switch on only when
you hold the button down. With the aid of the GPIO Zero, that’s easy. There
are two categories of the Button class called “ when_pressed” and “
when_released.” These don’t block the flow of the program, so if they are
entered in a loop, the program will continue to cycle unlimitedly. With that,
adjust your codes to something like this:
From gpiozero import LED, Button
From signal import pause
Led = LED(17)
Button = Button(2)
Button.when_pressed = led.on
Button.when_released = led.off
Pause()
Save the program and run it, when you press the button the LED will
illuminate. It will turn off again when the button is released.
Using a Buzzer
There are two basic types of a buzzer, active and passive. A passive buzzer
gives out a tone when a voltage is applied across it. It also requires a specific
signal to produce several tones. The active buzzers are much simpler to use,
so these are covered here.
Connecting a buzzer
You can interface an active buzzer in a way that's similar to that of LED,
however, due to the fact that they are a little more robust, a resistor won't be
needed to protect them.
Set up the circuit as shown in the Image below;
As stated, the
openings on a breadboard permit you to push the lead or metal legs of a
several electronic components into them and firmly hold them into the spot.
This attachment is sufficient enough such that to hold the parts to ensure they
don’t fall out of place, yet you can without much of a stress, snap-in or snap
out a component in case you need to change/supplant it from that place. The
breadboard is likewise referred to as solderless breadboards (less generally
used name) – simply because you don’t have to solder to bond the electronic
parts together.
In the figure above, you see a full-sized breadboard. On either side of the
breadboard, there are vertical lines or stripes normally marked with a ‘red and
dark’ or ‘red and blue’ lines and also bears + or – sign. These lines are termed
busses or rails and are used to convey power vertically to the whole circuit.
Normally, the holes close to the red line (+) sign will associate with the
positive battery terminal, and the holes close to the blue line (– ) sign will
interface with the negative battery terminal. The two segments within the
breadboard work on a level plane. What this implies is that, on the inside,
they are wired evenly, and when connected to a power source, the power
streams horizontally along the line of every segment. Therefore, if you check
row 1, the openings denoted as A, B, C, D, and E are connected, and the
openings in lines F, G, H, I, and J are connected ( this implies that power will
flow from A to E and F to J).
Let’s be more practical about how this works, you’ll need a:
- Breadboard
- LED light
- Male-to-female jumper leads
- Male-to-male jumper leads
- 1 Resistor 10 ohms, 9-volt battery, battery snap
What we want to set up a simple LED circuit on a Breadboard
Stage 1
Take the positive (red) and the negative (dark) ends of the battery snap and
place it above the power rails. After doing that, take the red wire and put one
end into the gap close to the red line, at that point, take the dark wire and
insert it into the gap close to the blue line.
Stage 2
Next, hold the Light Emitting Diode. Take the end of the LED that is longer
and put this into E15 and, after doing that, put the short end of the LED into
F 45. It is pertinent that you ensure you are inserting the appropriate legs of
the LED else the LED may get fused, and it will not illuminate.
Stage 3
Here, what you have to do is to take the jumper wire and put one of its ends
into opening C15, insert the other leg of the jumper wire into the power rail
hole 15, located 2 openings away from E15. In fact, you can insert it in any
opening on the power rail as the battery power is passing vertically through
the power rail, that is from the top to the bottom.
Stage 4
Well done, you’re doing perfectly fine, now, take a resistor and insert it into
this into 2 openings behind F45, i.e., H45 and afterward but insert the
opposite end of the resistor into the opening 45 of the power rail. In fact, you
can as well insert the other end into any opening on the power rail because
the battery power is passing vertically through the power rail as stated earlier.
Stage 5
Inspect and Check the association again (Steps 1 to 4). After you’re sure
everything is in place appropriately, connect the 9-volt battery to the battery
snap and the LED should glow, and there you have it!
With this demo, you’ve seen how to make use of a breadboard and how easy
it is, provided you know the appropriate connection patterns. Also, you
should have noticed how it is so natural to snap in and snap out parts.
CHAPTER TWELVE
Reading a Button on the Raspberry Pi
A good starter hardware project you can do with the Raspberry Pi is
attaching a simple tactile switch to the Raspberry Pi GPIO and also
detecting button functions in Python. Here, you'll gain the knowledge
about how to set up a circuit with the Raspberry Pi, as well as reading the
state of a button in Python. When you interface a button with Python, it
grants you an entry into unlimited possibilities of actions to carry out on a
button press. The items you'll need for this process include:
- A Raspberry Pi board that has been set up with the peripherals ( mouse,
keyboard, monitor, etc.)
- A solderless breadboard
- Jumper wire
-Resistor Pack
- A push-button, otherwise known as a tactical switch
- A multimeter, this is optional.
Setting up a Circuit
Interfacing the Raspberry Pi's multi-purpose input-output ports (GPIO) to an
instantaneous push button switch is a fairly basic circuit. One side of the
switch will be connected to an input pin on the Raspberry Pi, in this situation,
we use Pin 10. The opposite side of the switch will be connected to the 3.3V
mark on Pin 1 via a resistor. The resistor's function is to inhibit the current in
order to protect the input pin by regulating the quantity of current that can
flow through. The circuit is set up in this way
The notion
is that the input will be relatively low because it will be at zero volts when the
button is not pushed. Immediately you push the button, the pin will be
instantly connected to 3.3V, and it will become relatively high because it is a
3.3V now compared to 0V. When you clamp the electronic items together to
make a circuit, the reference diagram below might be of help in order to
locate the correct pin numbers.
def button_callback(channel):
print("Button was pushed!")
After this, our programs will start up with this input pin this way:
GPIO.setwarnings(False) # Ignore warning for now
GPIO.setmode(GPIO.BOARD) # Use physical pin numbering
GPIO.setup(10, GPIO.IN, pull_up_down=GPIO.PUD_DOWN) # Set pin 10
to be an input pin and set initial value to be pulled low (off)
Now that the pin has been tagged as an input pin, we can then attach an event
to it.
message = input("Press enter to quit\n\n") # Run until someone presses enter
GPIO.cleanup() # Clean up
With the codes combined, the output will resemble programs of this manner:
import RPi.GPIO as GPIO # Import Raspberry Pi GPIO library
def button_callback(channel):
print("Button was pushed!")
We're almost done, just hang in there. Now save the file and execute the
program via Thonny or command line with this code:
$ python3 push_button.py
From this moment onwards, you will notice that the program only displays
"Button was pushed!" anytime you press the button.
CHAPTER THIRTEEN
Using a Buzzer on the Raspberry Pi 4
A
CHAPTER FOURTEEN
Python Quick Reaction Game
I nelectronic
this project, you will develop a quick reaction game utilizing a couple of
components and a Python Script. Additionally, you might need a
breadboard, button, and a Light Emitting Diode. To be specific, you are
going to create a quick reaction game, which you will program with Python.
• Building the Circuit
The circuit you will use is
one that has two push-to-make buttons and an LED just as it is in the image
below.
Get hold of the tactile buttons and insert it into the holes on your breadboard,
with one set of legs inserted on row H and the other set inserted on row J. Do
the same with the second button, placing it at the other end of the breadboard
on the same row. After doing that, position an LED with the longer leg above
the ridge in the breadboard in D16 and the shorter leg in D15. The
numberings may vary depending on the breadboard, so ensure that you check
the diagram.
That being settled, insert one leg of the resistor into column(15), this would
be the short leg of the resistor, and the other leg into an opening along the
blue strip. This is the point where you include the jumper wires. Begin by
taking two male-to-male jumper wires and placing one end into an opening
close to the outside leg of the left hand button, and the opposite end in a hole
along the blue strip. Do the same for the right hand button. The next step now
is to insert GPIO14 into a hole on the breadboard in line with the other leg of
the left-hand button via a male-to-female jumper. Carry out this exact step for
the right-hand button, but here, you will connect it to GPIO15 instead.
With the aid of another male-to-female jumper wire, insert GPIO4 to a hole
on the breadboard in line with the long leg of the LED, then interface a GND
GPIO pin to the blue stripe on the breadboard with the unused male-to-
female jumper wire.
• Controlling the Light
When programming, it is advisable to deal with one problem at a time. Press
the Menu>Programming>Mu. After that, click on Save As and save the file
as reaction.py.
To start with, you have to bring in the modules and libraries that are essential
to control the GPIO pins on the Raspberry Pi 4. Input this:
Reaction.py
Gpiozero import LED, Button
From time import sleep
While you are outputting to a Light Emitting Diode, you should create the pin
through which the Light Emitting Diode connects to the Raspberry Pi in the
form of output. You have to employ a variable to name the pin and then
proceed to set the output.
Reaction.py
From gpiozero import LED, Button
From time import sleep
Led = LED(4)
The next thing to do is to add a couple of lines that will switch the Light
Emitting Diode on, hold on for five seconds and then switch the Light
Emitting Diode off.
Reaction.py
From gpiozero import LED, Button
From time import sleep
Led = LED(4)
Led.on()
Sleep(5)
Led.off()
After inputting all those, press Run to test the program.
In case the Light Emitting Diode doesn’t come on for about five seconds,
debug the program.
•Include an Element of Surprise
The primary aim of this game is to who presses the button immediately the
light goes off, therefore the timing should be randomized. Hence, an element
of surprise will be brought in, and few lines of codes need to be manipulated
in order to make this happen. Directly below “from time import sleep”
include a line to import uniform
From gpiozero import LED, Button
From time import sleep
From random import uniform
Led = LED(4)
Led.on()
Sleep(5)
Led.off()
In this situation, “Uniform” enables the random selection of a floating-point
number (decimal) out of a range of numbers. Now, pinpoint he line “Sleep
5” and adjust it such that it reads;
From gpiozero import LED, Button
From time import sleep
From random import uniform
Led = LED(4)
Led.on()
Sleep(uniform(5, 10))
Led.off()
Then click Save so that your program is saved and click Run to confirm its
effectiveness.
• Detecting the Buttons
The LED is now up and running, you might want to include a functionality in
your program so that the button is detected whenever it is pressed. In that
manner, you can record the scores of the players and see who emerges as the
winner. As usual, you’ll need to augment the codes of your current program
to be able to do this.
Open the reaction.py file and input these variables below led = LED(4):
From gpiozero import LED, Button
From time import sleep
From random import uniform
Led = LED(4)
Right_button = Button(15)
Left_button = Button(14)
Led.on()
Sleep(uniform(5, 10))
Led.off()
Then, directly below “led.off()”, you can insert a functionality that will be
called whenever you press the button, this will inform you about the pin the
button was on:
Led = LED(4)
Right_button = Button(15)
Left_button = Button(14)
Led.on()
Sleep(uniform(5, 10))
Led.off()
Def pressed(button):
Print(str(button.pin.number) + ‘ won the game’)
Right_button.when_pressed = pressed
Left_button.when_pressed =
Now Save the program the usual way and run it.
• Get Players Name
Another cool stuff is for the program to inform you about who won rather
than which button was pressed. You must first discover the players’ names.
You can use Input for this in Python. To discover the names of the players,
you can use “input” to enter their names—below the imported libraries and
modules, and the highlighted codes.
From gpiozero import LED, Button
From time import sleep
From random import uniform
Led = LED(4)
Right_button = Button(15)
Left_button = Button(14)
Left_name = input(‘left player name is ‘)
Right_name = input(‘right player name is ‘)
Led.on()
Sleep(uniform(5, 10))
Led.off()
Def pressed(button):
Print(str(button.pin.number) + ‘ won the game’)
Right_button.when_pressed = pressed
Left_button.when_pressed
With that, you can manipulate your pressed function, to enable it to print out
the name of the winner.
From gpiozero import LED, Button
From time import sleep
From random import uniform
Led = LED(4)
Right_button = Button(15)
Left_button = Button(14)
Left_name = input(‘left player name is ‘)
Right_name = input(‘right player name is ‘)
Led.on()
Sleep(uniform(5, 10))
Led.off()
Def pressed(button):
If button.pin.number == 14:
Print(left_name + ‘ won the game’)
Else:
Print(right_name + ‘ won the game’)
Right_button.when_pressed = pressed
Left_button.when_pressed
- Now Save the program and run it. Debug it if it doesn't work.
Another thing you might observe is that the game doesn’t quit when you push
the button, this can be corrected by including an exit into the “pressed”
From gpiozero import LED, Button
From time import sleep
From random import uniform
From sys import exit
Led = LED(4)
Right_button = Button(15)
Left_button = Button(14)
Left_name = input(‘left player name is ‘)
Right_name = input(‘right player name is ‘)
Led.on()
Sleep(uniform(5, 10))
Led.off()
Def pressed(button):
If button.pin.number == 14:
Print(left_name + ‘ won the game’)
Else:
Print(right_name + ‘ won the game’)
Exit()
Right_button.when_pressed = pressed
Left_button.when_pressed = pressed
In order to put the game into a loop so that the LED comes on again, remove
the exit ().
Well done!
Enjoy the game!
CHAPTER FIFTEEN
Virtual Gaming with the Raspberry Pi 4
A nother astonishing function of the Raspberry Pi 4 is its functionality in
Virtual Reality. However, carrying out this function on the Raspberry Pi
requires additional peripherals, gadgets, coding, etc. The project that will
be focused on is “Be Your Hero!.” This project will provide you with full
gesture control of any virtual Hero you want via a couple of inexpensive
devices using sensors. The entire data gathered is remotely transferred to a
computer and will show your favorite hero on a normal screen or a DIY HD
virtual reality headset. This project utilizes a blend of bracelets with 6-DOF
sensors and Wii Nunchuck that can be joined to your body. Those sensors
can identify “6 Degrees Of Freedom'' with a three-axis accelerometer and a
three-axis gyroscope. The central arrangement of all these embedded gadgets
is an Arduino FIO fueled by a Lipo battery. The communication is enabled
by an NRF24 Bluetooth board, which can balance the transmission channels.
On account of this gadget, there is an enormous number of modules while
interacting with a central solid Bluetooth stack.
The Bluetooth receptor is wired to an Arduino Micro. Inside this impressive
board, there is an atmega32u4 (same as Arduino Leonardo) installed which
enables it to imitate HID gadgets and COM ports simultaneously and on the
equivalent USB line. Through this, we can duplicate a console, a mouse, a
joystick simultaneously, and still send information over the serial terminal. A
Raspberry Pi device can analyze the flow of data and produce the results as
an interface over the HDMI. In like manner, you can as well utilize any
computer operating system as the code runs on Python. The Python code
enables its users with the these results:
- Full screen, which plays on the common everyday computer or TV screen
- Basic stereoscopic screen, to combine with cardboard
- Tunnel effect stereoscopic, to use on Virtual Reality headset coupled with
aspheric lenses.
- Furthermore, it provides users with several methods to communicate with
the “Be Your Hero” USB HID Sensor, the Keyboard, and the Mouse.
Quite a while prior, an incredible philanthropist of the Raspberry Pi
community manufactured Pi3D, an extraordinary light 3D Python library
running on the little CPU/GPU of our preferred PC. Here, we’ll combine a
Pi3D and VrZero. Also, we include a Blender which is free proficient
programming to fabricate 3D objects. By searching for 3D Blender objects on
the web, we’ll be provided with an unlimited amount of available drawings.
HID represents “ Human Interaction Devices,” a USB control used for
keyboards, mice and is apparently the easiest method to interact with a
computer because it is recognized by virtually every operating system.
Certain Arduino boards such as Leonardo or Micro aren’t utilizing the first
ATmega328p AVR chip as UNO, they execute an Atmega32u4. The name
doesn’t appear to be totally different, nevertheless this controller will give
you the chance to communicate with the USB port of a PC through HID. At
moments when you are playing with an Arduino UNO, you should add a chip
to interconnect the USB (like FTDI or 32u2) as HID is not compatible (aside
from V-USB for AVR library, yet the execution takes more time). This HID
capacity will give us an incredible method to interface among Bluetooth and
Raspberry Pi since we can re-utilize a portion of the Mouse or Keyboard
libraries for a straightforward interaction and furthermore utilize a Serial
terminal correspondence for more intricate information moves.
The hardware gadgets you’ll be making use of include:
- A Leonardo or Micro Arduino board. You can use the Micro if you intend
to manage space, however you’ll need an external 3.3V VCC in order to
power the Bluetooth. Meanwhile, Leonardo is embedded with a 3.3V power
supply which is capable of powering the Bluetooth.
- A NRF24L01+ on the SPI port
- You’ll also need a button. This safety button can restrict the HID because
there might be times when a wrong loop can cause your board to send
multiple keyboard and mouse commands. The essential feature of a button is
to carry out the command; “send nothing if button is pressed”
- Breadboard
- Load a 3D Python Map on Raspberry Pi or Any Other Platform
As you likely know, Python is now introduced on Raspberry Pi Debian, there
is a major community utilizing it, and it is anything but difficult to track
down some assistance. . Everything is very much reported from
establishment to recording and obviously running a few demos. When you
finish the installation, you can go to pi3d_demos and begin playing with all
the .py you come across.
- Prepare Your Hero for Blender Custom!
Now, the 3D environment has been launched, start searching for your
favorite Hero!! Blender is a verified software that can create and make
adjustments to 3D objects. However, being able to use the full capacity of the
tools provided is complex. Therefore, as a beginner, if you intend to create
your Hero from scratch, that may be too complicated for you to do. When
operating the Pi3d on a Raspberry Pi, you should be mindful of the
complexity of the object, the more the vertices and complex textures, the
slower the program will run.
- Enter Your Entity into Pi3d
When you see your favorite hero file, load it into Blender, the export option
can then be used to create a .obj and .mtl file. However, we need to get
familiar with certain things for us to successfully enter our object into pi3d :
Firstly, the .obj file that will be generated entails the shape, it is vital. Also ,
the generated .mtl file entails the links to the colours/ texture if you import
the texture of your hero from an external “.jpg” or “.png” file. Furthermore,
this MTL file likewise contains the paths to locate those textures and fit them
onto the appropriate surfaces. Therefore, it is very much advisable that you
store the entirety of the files in a similar folder, you do this via the “copy”
option when you export an object.
With that out of the way, we can now enter the entities into Pi3d by inputting
this command:
Self.body = pi3d.Model(file_string=”PathOfYourFile”)
In case you saved the .obj, the textures and the .mtl in one folder, the Pi3d
should recognize the textures and your hero should have colours. Generally,
every 3D file appears to have varying sizes, our Hero is probably going to
either have a large or small size. You can manipulate by inputting this:
Self.body.scale(X, X, X)
At this point, your hero should be on the map! However he’s not mobile.
- Transform your 3D Hero into Multiple Objects into Several objects
with Blender
Since you have imported your Hero as an entity, you can’t direct your Hero’s
parts independently. Now, we’ll revert to blender. Ideally, the goal is to
separate your Hero into multiple parts. If you bring in those multiple parts
into Pi3D as different objects, it will enable you to create interactions and
translations between objects. However, it is pertinent that you understand
certain blender functions;
Projects in Blender are termed “.blend”, if you have an “.obj”, you can come
up with a new project and use “import .obj”. The “copy” function comes in
handy when you export your “.obj” so the texture is compatible with the
version (paths inside “.mtl”). Include your full model, incase textures are
present, choose “object mode” at the base and then press “Alt a”. You will
see the textures. Here are some useful keys:
-Alter the focal point by pressing the shift and the central mouse button
-The function of key A is to either select or unselect everything.
-Change the orientation of your hero on the main three axes so it’s simplified
: keys “r x” “r y” “r z”. To make the import easier, always ensure you’re at a
similar reference.
- Incase you decide to rotate and centralize your hero in the center of the
grid, press the three arrows.
-Press “n” and fix the 3d cursor location to 0, 0, 0.
-If you are still present in object form, you can transfer the object/transform
/origin to the 3d cursor. This will enable the origin to the 3d cursor you fixed
at 0,0,0.
-Proceed to save your file as blender “Full_body_hero”
At this point, let’s get to splitting the hero:
Press “Save as,” then term your project as “head_hero” to keep the original
one. After that, choose “Edit mode” and “wire frame” at the base. You can
also use Solid to visualize if there's no mistake.
When you press “C”, it grants you access to the cursor. Choose all that you
want to remove and press X to get rid of them. When you’ve removed the
entire parts , press Vertex, you’ll find this at the right side of where you select
the mode. In a situation whereby you totally detach the neck from the head,
you will discover some sort of a hole inside. Right click on the entire
surrounding of the vertex of this hole and select it, then press “f” to develop a
face. If the resulting face is white, it usually means that you have selected the
vertex incorrectly.
With this, the first part of your hero is now available to you.You have to do
the same for all the parts you want to rotate. It’s a bit lengthy, but when you
become more familiar with blender, it becomes faster. Do not alter the parts
you are making to ensure that the cursor stays at 0.0.0. Your Hero will be
well assembled when you load it into Pi3d.
• Load Your Hero in Avatar.py File
What we have to do now is to load the hero into Pi3d, this is quite easy to do,
Just input this code
Self.body = pi3d.Model(file_string=”PATH TO THE BODY PART
.obj”, name=”Link”);
Then insert a shader to make the texture look more attractive. Try different
types and select which one suits you or your Hero , by writing this;
Shader = pi3d.Shader(“uv_flat”)
Input the scale to dimension your object, you’ll need to do this only once. In
the same manner, use the same procedure to create the head and merge the
body to it with this code:
Self.body.add_child(self.head)
ABOUT AUTHOR