Proyectos Raspberry Paython
Proyectos Raspberry Paython
Proyectos Raspberry Paython
The Raspberry Pi comes in a variety of form factors for different use cases. In
this case, you’ll be looking at the most recent version, the Raspberry Pi 4.
Below is the board layout of the Raspberry Pi 4. While this layout is slightly
different from previous models of the Raspberry Pi, most of the connections
are the same. The setup described in the next section should be the same for
both a Raspberry Pi 3 and a Raspberry Pi 4:
• General-purpose input–output pins: These pins are used to connect the Raspberry
Pi to electronic components.
• Ethernet port: This port connects the Raspberry Pi to a wired network. The
Raspberry Pi also has Wi-Fi and Bluetooth built in for wireless connections.
• Two USB 3.0 and two USB 2.0 ports: These USB ports are used to connect
peripherals like a keyboard or mouse. The two black ports are USB 2.0 and the two
blue ports are USB 3.0.
• AV jack: This AV jack allows you to connect speakers or headphones to the
Raspberry Pi.
• Camera Module port: This port is used to connect the official Raspberry Pi
Camera Module, which enables the Raspberry Pi to capture images.
• HDMI ports: These HDMI ports connect the Raspberry Pi to external monitors.
The Raspberry Pi 4 features two micro HDMI ports, allowing it to drive two
separate monitors at the same time.
• USB power port: This USB port powers the Raspberry Pi. The Raspberry Pi 4 has
a USB Type-C port, while older versions of the Pi have a micro-USB port.
• External display port: This port is used to connect the official seven-inch
Raspberry Pi touch display for touch-based input on the Raspberry Pi.
• microSD card slot (underside of the board): This card slot is for the microSD
card that contains the Raspberry Pi operating system and files.
A little later in this tutorial, you’ll use the components above to set up your Raspberry Pi.
Raspberry Pi vs Arduino
People often wonder what the difference is between a Raspberry Pi and an Arduino. The
Arduino is another device that is widely used in physical computing. While there is some
overlap in the capabilities of the Arduino and the Raspberry Pi, there are some distinct
differences.
The Raspberry Pi comes with a variety of software preinstalled, including a web browser,
an office suite, a terminal, and even Minecraft. The Raspberry Pi also has built-in Wi-Fi
and Bluetooth to connect to the Internet and external peripherals.
For running Python, the Raspberry Pi is often the better choice, as you get a full-fledged
Python installation out of the box without any configuration.
Running Python on the Raspberry Pi
One of the best things about working with Python on the Raspberry Pi is that Python is a
first-class citizen on the platform. The Raspberry Pi Foundation specifically selected
Python as the main language because of its power, versatility, and ease of use. Python
comes preinstalled on Raspbian, so you’ll be ready to start from the get-go.
You have many different options for writing Python on the Raspberry Pi. In this tutorial,
you’ll look at two popular choices:
Let’s start by looking at using the Mu editor to write Python on the Raspberry Pi.
The Raspbian operating system comes with several preinstalled Python IDEs that you can
use to write your programs. One of these IDEs is Mu. It can be found in the main menu:
When you open Mu for the first time, you’ll be given the option to select the Python mode
for the editor. For the code in this tutorial, you can select Python 3:
There’s a chance that Mu may not be preinstalled on your version of Raspbian. If Mu isn’t
installed, then you can always install it by going to the following file location:
This will open up a dialogue containing recommended software for your Raspberry Pi.
Check the box next to Mu and click OK to install it:
While Mu provides a great editor to get started with Python on the Raspberry Pi, you may
want something more robust. In the next section, you’ll connect to your Raspberry Pi over
SSH.
Often you won’t want to spend the time hooking up a monitor, keyboard, and mouse to
write Python on the Raspberry Pi. Luckily, Raspbian allows you to connect to the
Raspberry Pi remotely over SSH. In this section, you’ll learn how to enable and use SSH to
program Python on the Raspberry Pi.
Enable SSH
Before you can connect to the Raspberry Pi over SSH, you’ll need to enable SSH access
inside the Raspberry Pi Preferences area. Enable SSH by going to the following file path:
Once the configuration appears, select the Interfaces tab and then enable the SSH option:
You’ve enabled SSH on the Raspberry Pi. Now you need to get the IP address for the
Raspberry Pi so you can connect to it from another computer.
To access the Raspberry Pi remotely, you need to determine the IP address of the Raspberry
Pi on your local network. To determine the IP address, you need to access
the Terminal application. You can access Terminal here:
pi@raspberrypi:~ $ hostname -I
This will display the current IP address for your Raspberry Pi. With this IP address, you
can now connect to your Raspberry Pi remotely.
pi@raspberrypi:~ $
Now that you know how to connect, you’re ready to start programming Python on the
Raspberry Pi. You can get started right away using the Python REPL:
pi@raspberrypi:~ $ python3
Type in some Python to run it on the Raspberry Pi:
>>>
>>> print("Hello from your Raspberry Pi!")
Hello from your Raspberry Pi!
Awesome, you’re running Python on the Raspberry Pi!
Before you start building projects with Python on the Raspberry Pi, it’s a good idea to set
up a dedicated directory for your code. The Raspberry Pi has a full file system with many
different directories. Having a reserved place for your Python code will help keep
everything organized and easy to find.
Let’s create a directory called python-projects where you can store Python code for your
projects.
Using Mu
If you plan on using Mu to complete the projects in this tutorial, then you can use it now to
create the python-projects directory. To create this directory, you’ll want to do the
following:
Over SSH
If you’d rather use SSH to access your Raspberry Pi, then you’ll use the command line to
create the python-projects directory.
Note: Since you’ll be accessing the Raspberry Pi command line, you’ll need to use a
command-line text editor to edit your project files.
Both nano and vim come preinstalled on Raspbian and can be used to edit the project files.
You can also use VS Code to remotely edit files on the Raspberry Pi, but some setup is
required.
Let’s create the python-projects directory. If you aren’t currently logged into the
Raspberry Pi, then use the IP address of the Raspberry Pi to SSH into it from your
computer:
pi@raspberry:~ $
By default, when you SSH into the Raspberry Pi, you’ll start in the /home/pi directory.
Confirm this now by running pwd:
pi@raspberry:~ $ pwd
/home/pi
If for some reason you’re not in the /home/pi directory, then switch to it using cd
/home/pi:
pi@raspberry:~/Desktop $ cd /home/pi
pi@raspberry:~ $ pwd
/home/pi
Now in the /home/pi directory, create a new python-projects directory:
pi@raspberry:~ $ cd python-projects
pi@raspberry:~/python-projects $
Great! You’re ready to start coding your first circuits using Python on the Raspberry Pi.
Interacting With Physical Components
In this section, you’ll learn how to interact with different physical components using
Python on the Raspberry Pi.
You’ll be using the gpiozero library that comes preinstalled on Raspbian. It provides an
easy-to-use interface to interact with a variety of GPIO devices connected to the Raspberry
Pi.
Electronic Components
Before programming on the Raspberry Pi, you’ll need a few electronic components to build
the projects in the upcoming sections. You should be able to find each of the items below
on Amazon or at your local electronics store.
Breadboard
Breadboards follow a general layout. On the right and left sides, two rails run the length of
the breadboard. Every hole on these rails is connected. Generally, these are designated
positive (voltage, or VCC) and negative (ground, or GND).
On most breadboards, the positive rail is marked with a positive sign (+) and will have a
red line running next to it. The negative rail is marked with a negative sign (-) and has a
blue line running next to it.
On the interior of the board, component rails run perpendicular to the positive and
negative rails on the sides of the breadboard. Each of these rails contains holes for placing
components.
All holes in a single rail are connected. In the middle is a gutter separating the two sides of
the breadboard. Rails on opposite sides of the gutter are not connected.
Later in this tutorial, you’ll use these different rails to build full circuits that connect to the
Raspberry Pi.
Jumper Wires
Jumper wires allow you to prototype the connections of your circuit without having to
solder paths between GPIO pins and components. They come in three different types:
1. Male to male
2. Female to male
3. Female to female
It would be good to have at least ten to twenty of each type when you’re building your
Raspberry Pi projects in Python.
Other Components
Along with the breadboard and jumper wires, the projects in this tutorial will use the
following components:
With the required components in hand, let’s take a look at how you can connect them to the
Raspberry Pi using the GPIO pins.
GPIO Pins
The Raspberry Pi features forty GPIO pins along the top edge of the board. You can use
these GPIO pins to connect the Raspberry Pi to external components.
The pin layout below shows the different types of pins and their locations. This layout is
based on an overhead view of the pins with the Raspberry Pi’s USB ports facing you:
The Raspberry Pi features five different types of pins:
1. GPIO: These are general-purpose pins that can be used for input or output.
2. 3V3: These pins supply a 3.3 V power source for components. 3.3 V is also the
internal voltage that all GPIO pins supply.
3. 5V: These pins supply a 5 V power source, the same as the USB power input that
powers the Raspberry Pi. Some components, such as the passive infrared motion
sensor, require 5 V.
4. GND: These pins provide a ground connection for circuits.
5. ADV: These special-purpose pins are advanced and not covered in this tutorial.
In the next section, you’ll use these different pin types to set up your first component, a
tactile button.
Tactile Button
For your first circuit, you’re going to connect a tactile button to the Raspberry Pi. A tactile
button is an electronic switch that, when pressed, closes a circuit. When a circuit is closed,
the Raspberry Pi will register an ON signal. You can use this ON signal to trigger different
actions.
In this project, you’ll use a tactile button to run different Python functions based on the
state of the button. Let’s start by wiring the button to the Raspberry Pi:
1. Connect a female-to-male jumper wire from the Raspberry Pi’s GND pin to
the negative rail of the breadboard.
2. Place a tactile button across the gutter in the middle of the breadboard.
3. Connect a male-to-male jumper wire from the negative rail of the breadboard to
the row where the button’s bottom-left leg is placed.
4. Connect a female-to-male jumper wire from the Raspberry Pi’s GPIO4 pin to the
breadboard row where the button’s bottom-right leg is placed.
Note: If you’re having trouble finding a specific pin, then make sure to reference the GPIO
pin layout image when building your circuits. You can also purchase a breakout board for
easy breadboarding.
Inside the python-projects directory that you created earlier, save a new file
called button.py. If you’re using SSH to access your Raspberry Pi, then create the file like
this:
pi@raspberrypi:~/ cd python-projects
pi@raspberrypi:~/python-projects $ touch button.py
If you’re using Mu, then create the file with the following steps:
With the file created, you’re ready to start coding. Start by importing the Button class from
the gpiozero module. You’ll also need to import pause from the signal module. You’ll
look at why you need pause later:
button = Button(4)
Next, define functions that will be called for the different button events that are available on
a Button instance:
def button_pressed():
print("Button was pressed")
def button_held():
print("Button was held")
def button_released():
print("Button was released")
The Button class has three event properties: .when_pressed, .when_held,
and .when_released. These properties can be used to hook up different event functions.
While the .when_pressed and .when_released properties are self-
explanatory, .when_held requires a short explanation. If a function is set to
the .when_held property, then it will only be called if the button is pressed and held for a
certain amount of time.
Now that you know about the different event properties on Button, set each of these to
their respective functions that you defined earlier:
button.when_pressed = button_pressed
button.when_held = button_held
button.when_released = button_released
Great! You’ve got your button events set up. The last thing you need to do is to
call pause() at the end of the file. Calling pause() is required to keep the program
listening for the different events. If this wasn’t present, then the program would run once
and exit.
button = Button(4)
def button_pressed():
print("Button was pressed")
def button_held():
print("Button was held")
def button_released():
print("Button was released")
button.when_pressed = button_pressed
button.when_held = button_held
button.when_released = button_released
pause()
With the wiring complete and the code all set up, you’re ready to try out your first circuit.
Inside of the python-projects directory, run the program:
The program is now running and listening for events. Press the button, and you should see
the following in the console:
Since you used pause() in your code, you’ll need to manually stop the program. If you’re
running the program in Mu, then you can click Stop to quit the program. If you’re running
this from the command line, then you can stop the program with Ctrl + C .
With this first circuit under your belt, you’re ready to start controlling some other
components.
LED
For your next circuit, you’ll use Python to blink an LED on and off every
second. LED stands for light-emitting diode, and these components produce light when a
current is applied. You’ll find that they’re used everywhere in electronics.
Every LED has two legs. The longer leg is the positive leg, or anode. The electrical current
enters the LED through this leg. The shorter leg is the negative leg, or cathode. The current
exits the LED through this leg.
Current can only flow one direction through an LED, so make sure you’re connecting
jumper wires to the proper leg of the LED.
Here are the steps you’ll need to take to wire this circuit:
1. Connect a female-to-male jumper wire from the Raspberry Pi’s GND pin to
the negative rail of the breadboard.
2. Place an LED into two holes on the breadboard that are next to each other but not in
the same row.
3. Place the longer, positive leg of the LED into the hole on the right side.
4. Place the shorter, negative leg of the LED into the hole on the left side.
5. Place one end of a 330 Ω resistor into a hole in the same breadboard row as
the negative leg of the LED.
6. Place the other end of the resistor into the negative rail of the breadboard
7. Connect a female-to-male jumper wire from the Raspberry Pi’s GPIO4 pin to a
hole in the same breadboard row as the positive leg of the LED.
If the wiring looks good, then you’re ready to write some Python to get the LED blinking.
Start by creating a file for this circuit inside of the python-projects directory. Call this
file led.py:
led = LED(4)
Call the .blink() method on led:
led.blink()
Finally, add a call to pause() to make sure the program doesn’t exit:
pause()
Your complete program should look like this:
led = LED(4)
led.blink()
pause()
Save the file and run it to see the LED blink on and off:
Now you know how to control an LED with Python on the Raspberry Pi. For the next
circuit, you’ll be using Python to produce sound from the Raspberry Pi.
Buzzer
In this circuit, you’ll be wiring an active piezo buzzer to the Raspberry Pi. A piezo buzzer
emits a tone when current is applied. Using this component, your Raspberry Pi will be able
to generate sound.
Like LEDs, a buzzer has a positive and negative leg. The positive leg of the buzzer will
either be longer than the negative leg or there will be a positive sign (+) on the top of the
buzzer showing which leg is the positive leg.
With the wiring set up, let’s move on to the code. Create a file for this circuit inside
the python-projects directory. Call this file buzzer.py:
Start by importing Buzzer from the gpiozero module and pause from the signal module:
buzzer.beep(0.5, 0.5)
Finally, add a call to pause() to make sure the program doesn’t exit:
pause()
Your complete program should look like this:
buzzer = Buzzer(4)
buzzer.beep(0.5, 0.5)
pause()
Save the file and run it to hear the buzzer beep on and off every half second:
Note: If you’re using Mu, then there’s a chance that when you stop the program the tone
will continue. To stop the sound, remove the GND wire to break the circuit.
You may also need to restart Mu if the tone continues when you reconnect the GND wire.
Great! So far you’ve learned how to control three different types of electronic components
with Python on the Raspberry Pi. For the next circuit, let’s take a look at a slightly more
complex component.
Motion Sensor
In this circuit, you’ll be connecting a passive infrared (PIR) motion sensor to the
Raspberry Pi. A passive infrared motion sensor detects any motion in its field of vision and
sends a signal back to the Raspberry Pi.
When using a motion sensor, you may need to adjust how sensitive it is to motion and how
long it will send out a signal after motion is detected.
You can make adjustments using two dials on the side of the sensor. You’ll know which
dials they are because they’ll have a cross-shaped indentation in the center, which can be
adjusted with a Phillips-head screwdriver.
The image below shows these dials on the side of the motion sensor:
As the image shows, the left dial sets the signal timeout and the right dial sets the sensor
sensitivity. You can turn these dials clockwise or counterclockwise to adjust them:
You can adjust these based on your project needs, but for this tutorial turn both dials
counterclockwise all the way. This will set them to their lowest values.
Note: Occasionally, a motion sensor and a Raspberry Pi 3 will not work together correctly.
This results in occasional false positives from the sensor.
If you’re using a Raspberry Pi 3, then make sure to move the sensor as far from the
Raspberry Pi as possible.
Once you’ve adjusted the motion sensor, you’re ready to set up the wiring. The motion
sensor’s design doesn’t allow it to easily connect to a breadboard. You’ll need to connect
the Raspberry Pi’s GPIO pins directly to the pins on the motion sensor with jumper wires.
The image below shows the placement of the pins on the underside of the motion sensor:
1. Connect a female-to-female jumper wire from the Raspberry Pi’s 5V pin to the
sensor’s VCC pin.
2. Connect a female-to-female jumper wire from the Raspberry Pi’s GPIO4 pin to the
sensor’s OUT pin.
3. Connect a female-to-female jumper wire from the Raspberry Pi’s GND pin to the
sensor’s GND pin.
With the motion sensor adjusted and wired to the Raspberry PI, let’s take a look at the
Python code for detecting motion. Start by creating a file for this circuit inside the python-
projects directory. Call this file pir.py:
def motion():
print("Motion detected")
def no_motion():
print("Motion stopped")
print("Readying sensor...")
motion_sensor.wait_for_no_motion()
print("Sensor ready")
motion_sensor.when_motion = motion
motion_sensor.when_no_motion = no_motion
pause()
motion() is set to the .when_motion property and is called when the sensor detects
motion. no_motion() is set to the .when_no_motion property and is called when motion
has stopped for a certain period. This time is determined by the timeout dial on the side of
the sensor.
You’ll notice that before the .when_motion and .when_no_motion properties are set, there
is a call to .wait_for_no_motion() on the MotionSensor instance. This method will
pause the execution of the code until the motion sensor no longer detects any motion. This
is so that the sensor will ignore any initial motion that may occur as the program is starting
up.
Note: Motion sensors can sometimes be too sensitive or not sensitive enough. If you see
inconsistent results in the console when running the code above, then make sure to check
that everything is wired correctly. You may also need to adjust the sensitivity dial on your
sensor.
If your results are delayed in the console, then try adjusting down the .threshold property
on the MotionSensor instance. The default value is 0.5:
Motion detected
Now stop waving your hand in front of the sensor. After a few seconds, the following will
be displayed:
Motion stopped
Great! You can now detect motion with your Raspberry Pi. Once you’re done waving at
your Raspberry Pi, go ahead and hit Ctrl + C in the command line or press Stop in Mu to
terminate the program.
With this final circuit, you’ve learned how to use Python on the Raspberry Pi to control
four different components. In the next section, you’ll tie all of this together in a full project.
In this project, you’ll build a motion-activated alarm system that will flash an LED and
sound an alarm when it detects motion in a room. On top of this, you’ll use Python to save
a timestamp to a CSV file detailing each time motion occurs.
Wiring
1. Connect female-to-male jumper wires from the Raspberry Pi’s 5V and GND pins
to the positive and negative rails on the side of the breadboard.
2. Place an LED on the breadboard and connect the Raspberry Pi’s GPIO14 pin to the
LED with a female-to-male jumper wire.
3. Connect the LED’s negative leg to the breadboard’s negative rail through a 330 Ω
resistor.
4. Place a buzzer on the breadboard and connect the Raspberry Pi’s GPIO15 pin to
the buzzer with a female-to-male jumper wire.
5. Connect the buzzer’s negative leg to the breadboard’s negative rail with a male-
to-male jumper wire.
6. Connect a female-to-male jumper wire from the breadboard’s positive rail to the
sensor’s VCC pin.
7. Connect a female-to-female jumper wire from the Raspberry Pi’s GPIO4 pin to the
sensor’s OUT pin.
8. Connect a female-to-male jumper wire from the breadboard’s negative rail to the
sensor’s GND pin.
Okay, now that you have the circuit wired up, let’s dig into the Python code to set up your
motion-activated alarm system.
Code
As usual, start by creating a file for this project inside the python-projects directory. For
this project, call this file motion_detector.py:
import csv
from pathlib import Path
Next, import datetime from the datetime module so you can create a timestamp of the
motion event:
led = LED(14)
buzzer = Buzzer(15)
motion_sensor = MotionSensor(4)
Next, define the location of a CSV file that will store a timestamp each time motion is
detected. You’ll call it detected_motion.csv. Create a dictionary to hold the timestamp
values that will be written to the CSV:
output_csv_path = Path("detected_motion.csv")
motion = {
"start_time": None,
"end_time": None,
}
Create a method that saves the timestamp data to a CSV file. When the file is first created, a
header row is added:
def write_to_csv():
first_write = not output_csv_path.is_file()
Add a call to print() so you can watch the events occur while the program is running:
def start_motion():
led.blink(0.5, 0.5)
buzzer.beep(0.5, 0.5)
motion["start_time"] = datetime.now()
print("motion detected")
Then define an end_motion() function that will have the following behaviors:
You’ll also check that a motion["start_time"] value exists before running any of the
other code. You only want to write to the CSV if a start_time timestamp was recorded:
def end_motion():
if motion["start_time"]:
led.off()
buzzer.off()
motion["end_time"] = datetime.now()
write_to_csv()
motion["start_time"] = None
motion["end_time"] = None
print("motion ended")
Add a call to .wait_for_no_motion() so that any initial motion is ignored:
print("Readying sensor...")
motion_sensor.wait_for_no_motion()
print("Sensor ready")
Set the .when_motion and .when_no_motion properties on the MotionSensor instance:
motion_sensor.when_motion = start_motion
motion_sensor.when_no_motion = end_motion
Finally, end the code with a call to pause() to keep the program running. The full Python
code should look like this:
import csv
from pathlib import Path
from datetime import datetime
from gpiozero import LED, Buzzer, MotionSensor
from signal import pause
led = LED(14)
buzzer = Buzzer(15)
motion_sensor = MotionSensor(4)
output_csv_path = Path("detected_motion.csv")
motion = {
"start_time": None,
"end_time": None,
}
def write_to_csv():
first_write = not output_csv_path.is_file()
def start_motion():
led.blink(0.5, 0.5)
buzzer.beep(0.5, 0.5)
motion["start_time"] = datetime.now()
print("motion detected")
def end_motion():
if motion["start_time"]:
led.off()
buzzer.off()
motion["end_time"] = datetime.now()
write_to_csv()
motion["start_time"] = None
motion["end_time"] = None
print("motion ended")
print("Readying sensor...")
motion_sensor.wait_for_no_motion()
print("Sensor ready")
motion_sensor.when_motion = start_motion
motion_sensor.when_no_motion = end_motion
pause()
Save the file and run it to test out your new motion detector alarm:
Next Steps
You don’t have to stop here. There are many ways you could improve this project by
leveraging the capabilities of Python on the Raspberry Pi.
• Connect the Raspberry Pi Camera Module and have it take a photo whenever
motion is detected.
• Connect a speaker to the Raspberry Pi and use PyGame to play a sound file to
intimidate an intruder.
• Add a button to the circuit to allow a user to manually toggle motion detection on or
off.
There are many ways to upgrade this project. Let us know what you come up with!