0% found this document useful (0 votes)
9 views69 pages

Python Programming for Raspberry Pi 4

This document describes how to use Python and Raspberry Pi 4 for electronic projects. It briefly explains Python and Raspberry Pi, then describes how to set up a Raspberry Pi 4, install Python and IDLE, and program the Raspberry Pi 4 to control and monitor electronic devices using the GPIO pins through Python. Next, it presents several example projects that use LED diodes and a DIP switch to demonstrate how to read input data and write output.

Translated by

ScribdTranslations
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views69 pages

Python Programming for Raspberry Pi 4

This document describes how to use Python and Raspberry Pi 4 for electronic projects. It briefly explains Python and Raspberry Pi, then describes how to set up a Raspberry Pi 4, install Python and IDLE, and program the Raspberry Pi 4 to control and monitor electronic devices using the GPIO pins through Python. Next, it presents several example projects that use LED diodes and a DIP switch to demonstrate how to read input data and write output.

Translated by

ScribdTranslations
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1

PYTHON AND RASPBERRY PI 4 FOR ELECTRONICS

Angie Liceth Pinillos Rodgers


Electronic Engineer
Specialist in Pedagogy for the Development of Autonomous Learning
SENA Instructor
2

PYTHON AND RASPBERRY PI 4 FOR ELECTRONICS

By: Angie Pinillos Rodgers

Angie Liceth Pinillos Rodgers


Electronic Engineer
Specialist in Pedagogy for the Development of Autonomous Learning
SENA Instructor
3

About the Author

ANGIE LICETH PINILLOS RODGERS

• Technician in Radio, TV, Sound and


Betamax graduated in 1990
• Technician in Digital Electronics and
Industrial graduated in 1991
• Graduated in Electronic Engineering
1999
• Specialist in Pedagogy For the
Development of Autonomous Learning
graduated in 2004.
• Embedded Systems Specialist

I have the labor competencies in the standards:

• MAINTAIN AUDIO ELECTRONIC EQUIPMENT


• GUIDE FACE-TO-FACE TRAINING PROCESSES BASED ON
IN THE ESTABLISHED TRAINING PLANS.

Instructor in the area of Electronics and Automation at the Center of


Mining Operation and Maintenance of SENA Regional Cesar, position that
performance since 1995.

Angie Liceth Pinillos Rodgers


Electronic Engineer
Specialist in Pedagogy for the Development of Autonomous Learning
SENA Instructor
4

INDEX
About the Author ..................................................................................................................3

INDEX......................................................................................................................................4

1. INTRODUCTION

[Link] PI ..........................................................................................................6

[Link]......................................................................................................................6

2. KNOWING THE GPIO OF THE RASPBERRY PI .........................................................7

3. PREPARING THE RASPBERRY PI 4B ...........................................................................9

[Link] ELEMENTS......................................................................................9

3.2. WRITE THE RASPBERRY PI OS OPERATING SYSTEM ON THE MICRO-SD CARD..10

3.3. DOWNLOAD AND INSTALL PuTTy15

3.4. CONNECTING WITH THE RASPBERRY PI18

3.5. INSTALLING VNC VIEWER ON THE COMPUTER..................................................21

3.6. USING VNC VIEWER.............................................................................................24

4. PYTHON

4.1. CHARACTERISTICS OF THE LANGUAGEE 27

4.1.1. Advantages.............................................................................................................27

4.1.2. Disadvantages .......................................................................................................28

4.2. IDLE ON THE RASPBERRY PI 28

4.2.1. INSTALLATION FROM THE IDLE ......................................................................................28

4.2.2. IDLE AS AN INTERACTIVE ENVIRONMENTO ...............................................................29

4.2.3. IDLE AS A PROGRAM EDITOR31

5. PROGRAMMING THE RASPBERRY PI 4B...................................................37

5.1. PROGRAMMING THE GPIO AS OUTPUT..........................................................39


Angie Liceth Pinillos Rodgers
Electronic Engineer
Specialist in Pedagogy for the Development of Autonomous Learning
SENA Instructor
5

5.2. PROGRAMMING THE GPIO AS INPUT.......................................................41

5.3. USING FUNCTIONS IN PYTHON...........................................................................43

5.3.1. Define a function43

5.4. USING LISTS IN PYTHONN ....................................................................................47

5.5. USING for EN PYTHON ..........................................................................................47

5.6. USING if-else IN PYTHONN 48

5.7. USING while in Python50

6. PROJECTS WITH DIPSWITCH AND LEDS WITH THE RASPBERRY PI 4B .......................51

6.1. WRITE IN THE LEDS THE DATA READ BY THE DIPSWITCH V1 ...............................53

6.2. WRITE IN THE LEDS THE DATA READ BY THE DIP SWITCH V2 ...............................56

6.3. WRITE IN THE LEDS THE DATA READ BY THE DIPSWITCH V3 ...............................59

6.4. WRITE IN THE LEDS THE DATA READ BY THE DIPSWITCH V4 ...............................60

6.5. WRITE IN THE LEDS THE DATA READ BY THE DIPSWITCH V5...............................61

6.6 WRITE IN THE LEDS THE DATA READ BY THE DIPSWITCH V6 ...............................62

6.7 WRITE IN THE LEDS THE DATA READ BY THE DIPSWITCH V7 ...............................64

Angie Liceth Pinillos Rodgers


Electronic Engineer
Specialist in Pedagogy for the Development of Autonomous Learning
SENA Instructor
6

1. INTRODUCTION
[Link] PI
Raspberry Pi is an exceptional device: a fully functional computer in
a small and low-cost format. Whether you want a device for browsing
Internet as if it is for playing, or if you want to learn to write your own programs or
create your own circuits and physical devices, Raspberry Pi (and its amazing community)
it helps you at every step.

Raspberry Pi is what is known as a single-board computer, which is


exactly what its name indicates: like a desktop computer, a laptop
or a smartphone, but built on a single printed circuit board. Like
most single-board computers, Raspberry Pi is small—more than
smaller than a credit card—but that doesn't stop it from being powerful:
a Raspberry Pi can do anything that a larger computer can do and
of greater consumption, although it may not do so as quickly.

[Link]
Technically, Python is a high-level programming language.
object-oriented, with an integrated dynamic semantics, primarily for the
web development and computer applications.

It is very attractive in the field of Rapid Application Development (RAD) because


offers dynamic typification and dynamic binding options.

Python is relatively simple, so it is easy to learn, as it requires


a unique syntax that focuses on readability. Developers can read and
translate Python code much more easily than other languages.

Angie Liceth Pinillos Rodgers


Electronic Engineer
Specialist in Pedagogy for the Development of Autonomous Learning
SENA Instructor
7

2. KNOWING THE GPIO OF THE


RASPBERRY PI
The GPIO (General Purpose Input Output) pins of the Raspberry Pi allow us to
interact with the outside world and, of course, with the electronics that surround it. They are
pins or terminals that are designed to communicate with the most diverse
electronic devices that we want to control or from which we want to obtain
data and general information.

Each pin of the GPIO port has its purpose, several pins working together.
they can form a particular circuit. The GPIO port design on a Raspberry Pi
4 can be seen in figure 2.1.

Figure 2.1. GPIO Port of Raspberry Pi 4B

The pin numbering of the GPIO port is divided into two columns, the
the right column takes the even numbers and the left column takes the
odd numbers.

The heart of the Raspberry Pi 4B is a BCM271 chip with a 64-bit architecture.


It has four ARM A72 cores and the processor speed is 1.5GHz.

Angie Liceth Pinillos Rodgers


Electronic Engineer
Specialist in Pedagogy for the Development of Autonomous Learning
SENA Instructor
8

difference of traditional microprocessors, these are designed to be


used in embedded systems.

When a pin is an input, the program can read whether it has a high level or
low voltage. When, on the contrary, the pin is an output, the program can
generate a high or low voltage on that pin.

Although the GPIO port of the Raspberry Pi 4B offers a power supply of 5V,
coming from the power input of the USB Type-C connector, its
internal operation is based on 3.3V logic Connect a 5V voltage to
any pin of the GPIO port of the Raspberry Pi 4B, or short circuit
directly with either of the two power pins (Pin2 and
Pin4) to any other pin will irreversibly damage the Raspberry Pi because
the port is directly connected to the pins of the SoC BCM2711 processor.

Angie Liceth Pinillos Rodgers


Electronic Engineer
Specialist in Pedagogy for the Development of Autonomous Learning
SENA Instructor
9

3. PREPARING THE RASPBERRY PI 4B


3.1. NECESSARY ELEMENTS
We are going to use the Raspberry Pi by connecting it to a PC via the interface.
VNC, for this only the following elements are needed:

• USB power supply - 5 V and 3 amperes (3 A), with a USB connector


Type C. The official power supply for Raspberry Pi is the option
recommended, as it is capable of coping with the changing demands
Raspberry Pi energy.

• microSD card - The microSD card acts as permanent storage of


Raspberry Pi; all the files you create and the software you install, along with the
own operating system, are stored on the card. An 8 GB card is
enough to get started, although a 16 GB one offers more space for
to progress.

Angie Liceth Pinillos Rodgers


Electronic Engineer
Specialist in Pedagogy for the Development of Autonomous Learning
SENA Instructor
10

[Link] THE RASPBERRY PI OS OPERATING SYSTEM ON THE CARD


MICRO-SD
The program responsible for writing the Raspberry Pi OS software onto the micro-
It is called Raspberry Pi Imager, which must be downloaded from the following page.
Raspberry Pi OS– Raspberry Pi

Download the software corresponding to your computer's operating system.

Go to the downloads folder on your computer and double click on the


file imager_1.7.2

Click on YES

Click on Install

Angie Liceth Pinillos Rodgers


Electronic Engineer
Specialist in Pedagogy for the Development of Autonomous Learning
SENA Instructor
11

Upon finishing the installation, click on Finish

It's time to write the operating system to the micro-SD card, insert the memory.
micro-SD in the corresponding port of your computer.

Click on CHOOSE OS

Angie Liceth Pinillos Rodgers


Electronic Engineer
Specialist in Pedagogy for the Development of Autonomous Learning
SENA Instructor
12

Click on Raspberry Pi OS (other)

Click on Raspberry Pi OS Full (32-bit)

Click on CHOOSE STORA..

Click on your micro-sd card

Click on settings

Choose the following options:

Angie Liceth Pinillos Rodgers


Electronic Engineer
Specialist in Pedagogy for the Development of Autonomous Learning
SENA Instructor
13

• In image customization option = to always use.

• We check the Set hostname box and write a name.

• We checked the Enable SSH box to be able to communicate.


later with the raspberry pi from our computer.

• We check the box Set locale settings and choose our time zone

• We write a username for our Raspberry and a


access password.

• We click on SAVE

Angie Liceth Pinillos Rodgers


Electronic Engineer
Specialist in Pedagogy for the Development of Autonomous Learning
SENA Instructor
14

Click on WRITE

A warning appears that all data on the micro SD card will be deleted.
Click on YES

After finishing writing and verifying the writing on the micro SD card, remove the memory.
micro SD of the computer, Click on CONTINUE

Close the Raspberry Pi Imager program

Insert the micro-SD card into the Raspberry Pi and connect the power adapter.

Angie Liceth Pinillos Rodgers


Electronic Engineer
Specialist in Pedagogy for the Development of Autonomous Learning
SENA Instructor
15

To communicate with the Raspberry Pi 4B, we initially need a terminal.


that supports SSH (PuTTy) to send some commands and activate the connection by
VNC.

[Link] AND INSTALL PuTTy

PuTTY is a free terminal emulator that supports SSH and many others.
protocols. Most users, especially those working on systems
Windows operatives find it very useful when connecting to a Unix server or
Linux via SSH.

To download the PuTTy program, go to the following page


[Link]

Click on Download PuTTy

Click on the option for your operating system

Once the download is complete, go to the downloads folder on your computer.

Double click on the file [Link]

Angie Liceth Pinillos Rodgers


Electronic Engineer
Specialist in Pedagogy for the Development of Autonomous Learning
SENA Instructor
16

Click on Next

Click on Next

Angie Liceth Pinillos Rodgers


Electronic Engineer
Specialist in Pedagogy for the Development of Autonomous Learning
SENA Instructor
17

Click on Install

Haga clic en SI

Click on Finish

Angie Liceth Pinillos Rodgers


Electronic Engineer
Specialist in Pedagogy for the Development of Autonomous Learning
SENA Instructor
18

[Link] WITH THE RASPBERRY PI


To connect to the Raspberry PI, we open the PuTTy software, to do that, please
double click on the desktop icon

We write the Host name of our Raspberry Pi and click on Open

Angie Liceth Pinillos Rodgers


Electronic Engineer
Specialist in Pedagogy for the Development of Autonomous Learning
SENA instructor
19

Click on Accept

Type your Raspberry Pi username and press <Enter>

Type the password for your Raspberry Pi and press <Enter>

It is ready to send commands to the Raspberry Pi

Angie Liceth Pinillos Rodgers


Electronic Engineer
Specialist in Pedagogy for the Development of Autonomous Learning
SENA Instructor
20

To enable the graphical mode, type the following command: sudo raspi-config
the PuTTy terminal and press <Enter>

Use the down arrow to locate us in Interface Options and press <Enter>

Using the down arrow, locate VNC and press <Enter>

Use the tab key to position yourself on Yes and press <Enter>

Type <Enter>

Use the tab key to navigate to Finish and press <Enter>

Angie Liceth Pinillos Rodgers


Electronic Engineer
Specialist in Pedagogy for the Development of Autonomous Learning
SENA Instructor
21

3.5. INSTALLING VNC VIEWER ON THE COMPUTER


To install VNC (Virtual Network Computing) on the computer, we need to download
the software at the following addressDownload VNC Viewer | VNC Connect ([Link]).

Click on Download VNC Viewer

Once the file has been downloaded, go to the download folder on your computer.
and double click on the file [Link]

Select your language and click Accept

Click Next

Angie Liceth Pinillos Rodgers


Electronic Engineer
Specialist in Pedagogy for the Development of Autonomous Learning
SENA Instructor
22

Click the checkbox to Accept the terms of the contract.


license and then click Next

Click on next

Angie Liceth Pinillos Rodgers


Electronic Engineer
Specialist in Pedagogy for the Development of Autonomous Learning
SENA Instructor
23

Click on Install

Click on YES

Angie Liceth Pinillos Rodgers


Electronic Engineer
Specialist in Pedagogy for the Development of Autonomous Learning
SENA Instructor
24

Click on Finish

[Link] VNC VIEWER


To use the Raspberry Pi with our computer, we must open the VNC program.
Viewer, for that double click on the desktop icon

Click on YES

Angie Liceth Pinillos Rodgers


Electronic Engineer
Specialist in Pedagogy for the Development of Autonomous Learning
SENA Instructor
25

Click on File–New Connection

You must enter the host name that you wrote when setting up the Raspberry Pi and click
in Accept

Double click on the icon

Angie Liceth Pinillos Rodgers


Electronic Engineer
Specialist in Pedagogy for the Development of Autonomous Learning
SENA Instructor
26

In the following dialog box, enter the username and the password that
I set up the Raspberry Pi and click on Accept

Our Raspberry should be visible on our computer

Angie Liceth Pinillos Rodgers


Electronic Engineer
Specialist in Pedagogy for the Development of Autonomous Learning
SENA Instructor
27

4. PYTHON
Python is a high-level programming language created in the late 80s.
principles of the 90s by Guido van Rossum, a Dutchman who was working at that time
at the Center for Mathematics and Computer Science in the Netherlands. Your instructions
they are very close to natural language in English and emphasis is placed on readability
from the code. It takes its name from Monty Python, a comedy group from the 60s that
Guido liked them a lot. Python was created as a successor to the ABC language.

4.1. CHARACTERISTICS OF LANGUAGE


Based on its definition from Wikipedia:

• Python is an interpreted, multi-platform programming language whose


philosophy emphasizes a syntax that favors readable code.

• It is a multiparadigm programming language, as it supports


object-oriented, imperative programming, and to a lesser extent,
functional programming.

[Link]

• Free and open source.

• Easy to read, similar to pseudocode.

• Relatively easy and quick learning: clear, intuitive

• High level.

• High Productivity: simple and fast.

• It tends to produce good code: order, cleanliness, elegance, flexibility

• Multiplatform. Portable.

• Multiparadigm: imperative, object-oriented, functional programming

• Interactive, modular, dynamic.

• Extensive libraries.

Angie Liceth Pinillos Rodgers


Electronic Engineer
Specialist in Pedagogy for the Development of Autonomous Learning
SENA Instructor
28

• Large number of third-party libraries.

• Extensible (C++, C, …)

• Great community, extensive support.

• Interpreted.

• There are different implementations: CPython, PyPy, Jython, IronPython,


MicroPython

4.1.2. Disadvantages

• Interpreted (execution speed, multithreading vs GIL, etc.).

• Memory consumption.

• Errors during execution.

• Two major versions not entirely compatible (v2 vs v3).

• Mobile development.

• Documentation sometimes scattered and incomplete.

• Several modules for the same functionality.

• Third-party libraries are not always fully mature.

4.2. IDLE ON THE RASPBERRY PI


IDLE (Integrated Development Environment for Python) is a graphical environment for
elementary development that allows editing and executing programs in Python.

IDLE is also an interactive environment where instructions can be executed.


Python snippets.

4.2.1. INSTALLATION OF THE IDLE

To install the IDLE, the Raspberry Pi 4B must be turned on and have communication.
with the computer through VNC.

Angie Liceth Pinillos Rodgers


Electronic Engineer
Specialist in Pedagogy for the Development of Autonomous Learning
SENA Instructor
29

We open the command terminal of the Raspberry PI

We typed the command: sudo apt-get install python3

We typed the command: sudo apt-get install idle3

[Link] AS AN INTERACTIVE ENVIRONMENT

When opening IDLE with the shortcut Start > Programming > IDLE (using Python-3.9), it
it will open the main IDLE window, as shown in the following image.

Angie Liceth Pinillos Rodgers


Electronic Engineer
Specialist in Pedagogy for the Development of Autonomous Learning
SENA Instructor
30

IDLE: Main Window

This window shows the installed version of Python.

Note: The IDLE window has a default size of 80 x 40 characters.


It can be modified with the menu Options > Configure IDLE > Windows.

IDLE: General options

The main window of IDLE is an interactive Python environment where you can
write Python commands to the right of the prompt symbol >>>
When you press Intro, IDLE will execute the command immediately. If the command produces
any result, this will be displayed in blue and without the request symbol. For example,
It can be verified that Python knows how to add two plus two:
Angie Liceth Pinillos Rodgers
Electronic Engineer
Specialist in Pedagogy for the Development of Autonomous Learning
SENA Instructor
31

Upon finishing executing the command, IDLE shows the prompt symbol again.
waiting for a new order.

In the interactive environment of IDLE, previous commands can be retrieved using the
keyboard shortcuts:

Alt+p to see the previous instruction (I suppose p is for previous, in Spanish,)


previous)
Alt+n to see the next instruction (I suppose n is for next, in Spanish,
next)

[Link] AS A PROGRAM EDITOR

IDLE is also a basic program editor that allows you to write programs,
store them in files and execute them.

The main window of IDLE is always the interactive environment, but it is also the
window where the programs will be executed.

To create a program file with IDLE, open a new window using the
File menu > New File (or the keyboard shortcut Ctrl+N).

By selecting this option, a new window like the one in the image will open.

Angie Liceth Pinillos Rodgers


Electronic Engineer
Specialist in Pedagogy for the Development of Autonomous Learning
SENA Instructor
32

This window no longer displays the request symbol because it is simply a


text editor (that colors Python code). That's why the menus of this window
They are not the same as those in the main window of IDLE.

For example, write the program:

You will notice that in this window, when you press <Enter>, the command does not execute as
it happens in the interactive environment, but it simply moves to the next line.

To save the program, choose the option from the menu File > Save or File > Save As ...
(you can also use the keyboard shortcut Ctrl+S).

The first time I save a program, the standard dialog window will open.
Windows. Choose the folder and the file name. The usual extension of the
Python programs are .py. If you don't write the extension, IDLE will add it.
automatically.

Angie Liceth Pinillos Rodgers


Electronic Engineer
Specialist in Pedagogy for the Development of Autonomous Learning
SENA Instructor
33

Once the program is saved, the file name appears in the title bar.
from the window.

Colors in the programs

Both in the interactive environment and when editing a program, IDLE colorizes the text of
agreement with its syntax. Colors help identify the different types of elements
and to locate errors:

The reserved words of Python (those that are part of the language) are shown
in orange.
The strings of text are shown in green.
Las funciones se muestran enpúrpura.
The results of the orders are written in blue.
Error messages are displayed in red.

Run Python programs in IDLE

In order to run a program edited in IDLE, it is first necessary to save it.


Una vez haya guardado el programa, puede ejecutarlo mediante la opción del menú
Run > Run module (you can also use the F5 key).

Angie Liceth Pinillos Rodgers


Electronic Engineer
Specialist in Pedagogy for the Development of Autonomous Learning
SENA Instructor
34

The output of the program will be displayed in the main IDLE window.

The work procedure is always the same: write or modify the program in
the secondary window, save it, run it and, if applicable, the program output is
It will display in the main window. If you want, you can have several secondary windows.
simultaneously open, but the execution of the programs always takes place in
the main window.

You can also run previously created programs in IDLE by opening them.
previously.

From IDLE, you can open the menu File > Open:

Once the program is open in IDLE, run it by pressing F5 or through the Run menu.
Run module.

Errors in the programs

If an error occurs or is found while executing an instruction or a program


any syntax error, Python generates an error message in English that indicates where
an error has occurred and a description of the type of error. The error message is
display in a modal window or in the main IDLE window.

Angie Liceth Pinillos Rodgers


Electronic Engineer
Specialist in Pedagogy for the Development of Autonomous Learning
SENA Instructor
35

The following example is an example of a syntax error, specifically that the


parentheses that must enclose the arguments of any function in this case, the
print() function.

If it is a syntax error, the source of the error can be found exactly


at the point indicated by Python, but it can also be found at a point
previously of the program that Python cannot identify. For example, if a string
it does not close, Python will indicate that at the end of the program it has found an unclosed string
close, but Python cannot identify where we should have closed the string.

• If the instruction has been written in the interactive environment, the error message will be
shows in the IDLE window:

• If the same order has been written in a program, like before executing a
the program checks its syntax, this error is detected before executing the
the program and IDLE show the error message in a pop-up window:

The following example is an example of an error that occurs when executing a statement.
Specifically, the error is due to the word hello not being in quotes and Python
it is understood that it refers to a variable called hello but since it is not present
Since no variable named that has been previously defined, an error occurs. As the
error occurs when the instruction is already executing, IDLE always shows the
message in the interactive environment, although the text is not exactly the same:

• If the instruction has been written in the interactive environment, the error message will
show in the IDLE window:

Angie Liceth Pinillos Rodgers


Electronic Engineer
Specialist in Pedagogy for the Development of Autonomous Learning
SENA Instructor
36

• If the instruction has been written in a program, the error message will also
show in the IDLE window:

Angie Liceth Pinillos Rodgers


Electronic Engineer
Specialist in Pedagogy for the Development of Autonomous Learning
SENA Instructor
37

5. PROGRAMMING THE RASPBERRY PI 4B


To program the GPIO ports of our Raspberry Pi, we must go to start >
Programming > IDLE (using Python-3.9)

The IDLE must be opened.

The next step is to open the program editor, for that you must go to the menu File > New
File (or the keyboard shortcut Ctrl+N).

La ventana del editor de programa debe verse de la siguiente manera

Angie Liceth Pinillos Rodgers


Electronic Engineer
Specialist in Pedagogy for the Development of Autonomous Learning
SENA Instructor
38

Before writing any instructions, it is recommended that you save the program, in order to
you should click on File > Save As…, it is recommended to choose an appropriate name
program and not use whitespace between characters

We choose the directory where it will be saved and click on Save.

Angie Liceth Pinillos Rodgers


Electronic Engineer
Specialist in Pedagogy for the Development of Autonomous Learning
SENA Instructor
39

5.1. PROGRAMMING THE GPIO AS OUTPUT


The output pins are used to connect the actuators which are the
in charge of managing the power devices.

As an example, we will use the following diagram. As can be observed, it has


a LED connected to GPIO18 of the Raspberry Pi 4B, with its respective current limiting resistor
of current. The value of the current limiting resistor must be calculated considering

tell the following formula = Please note that the GPIOs of the Raspberry
Pi 4B supplies 3.3V

Making the connections on the protoboard, it would look like:

Angie Liceth Pinillos Rodgers


Electronic Engineer
Specialist in Pedagogy for the Development of Autonomous Learning
SENA Instructor
40

In our program, the first thing to do is to import the libraries that


we will need, the first of them is [Link] as GPIO, which allows controlling the
pins GPIO from the code.

The second library we are going to use is Estime, which allows for delays.
time in our program.

The main function of the program is defined with the instruction def main ():

Once the libraries to be used are imported, the GPIO library should be set to the mode
for the Board or BCM mode, the instruction [Link]([Link]) is used.

Next, we set the GPIO pins as output with the instruction [Link],
the general instruction is [Link](pin, configuration); where pin is the number of the
GPIO and configuration is [Link], if the pin is output or [Link], if the pin is input.

To set a HIGH state on a GPIO configured as output, the following is used


[Link](pin, True), where pin is the GPIO number.

To set a LOW state on a GPIO configured as output, the


[Link](pin, False), where pin is the GPIO number.

Angie Liceth Pinillos Rodgers


Electronic Engineer
Specialist in Pedagogy for the Development of Autonomous Learning
SENA Instructor
41

The hello world of microcontrollers is making an LED blink, so you


needs the instruction [Link](x), where x is the number of seconds that
we want to delay

Our complete program would be like this.

5.2. PROGRAMMING THE GPIO AS INPUT


When a pin is configured as a digital input, it can be connected to
any digital sensor, a digital sensor is one that has two outputs
states, HIGH or LOW;

An example of this type of sensors are switches, push buttons, sensor of


movement, presence sensor, capacitive sensor, inductive sensor.

As an example, we will use the following diagram. As can be seen, there is


a LED connected to GPIO18 and a button connected to GPIO4 of the Raspberry Pi 4B.

Angie Liceth Pinillos Rodgers


Electronic Engineer
Specialist in Pedagogy for the Development of Autonomous Learning
SENA Instructor
42

Making the connections on the protoboard would leave us with:

Let's remember that the first thing to do is to import the libraries that
we will need, [Link] as GPIO, time

The main function of the program is defined with the instruction def main ():

Angie Liceth Pinillos Rodgers


Electronic Engineer
Specialist in Pedagogy for the Development of Autonomous Learning
SENA Instructor
43

The GPIO library is set to Board mode or to BCM mode.


[Link]([Link])

The GPIOs are configured as input or output [Link](pin, configuration)

To read the state of a GPIO configured as input, the instruction is used


[Link](pin), where pin is the GPIO number

Reading the state of a GPIO is useful for making decisions; for this purpose, it uses the
if-else conditional statement

[Link] FUNCTIONS IN PYTHON


A function is nothing more than a block of code that has a name and receives
some input arguments or none, to be able to carry out a certain
operation and in the end it returns a result.

The best part is that we can call this block as many times as
we want.

When we use functions within a programming language, we enter into the


well-known paradigm of structured programming whose advantages are:

modularization: divide the program into different modules to allow for its readability and
simplify the complexity of the problem

reuse: it prevents us from constantly repeating the same code, since


we can call the function as many times as we want.

5.3.1. Define a function

Functions in Python are defined using the def statement.

Angie Liceth Pinillos Rodgers


Electronic Engineer
Specialist in Pedagogy for the Development of Autonomous Learning
SENA Instructor
44

The def statement in python is a definition which is used to create


user-defined functions programmed for modularization and reuse
of codes. Its syntax is shown below:

The above syntax highlights different stages that can be emphasized at the moment.
to create a function in python which we describe below:

function name: The name of the function will refer to the objective for the
What was created by this block of code. It is a good practice to write this name.
in lowercase letters.

Input Parameters: The input parameters are the external variables of the
necessary functions for the execution of the internal program within the function, the
What the user must provide at the time of calling the function.

What is the docstring in Python?: The docstrings is documentation made up of


a string of characters that is integrated into all objects within Python
and its purpose is to describe in detail what the object is used for and how it is used.

Therefore, as you can see in the function, immediately after defining the
name, here comes the docstring that will describe to the user the purpose of the function and
It will show you how to use it. That is, how to make the call.

to be able to read the function's docstring we type: help(function_name)

Sentences: In this stage, the block of Python code is developed that contains the
programming logic of the function, using the input parameters that
They were referenced by the user in order to achieve the expected result.

What the return function does in Python: The return statement in Python ends the
execution of the function as such and returns control to the calling function or
stage where the function was called to continue with the normal flow of code.

With return, we can also return the expected value of the function so that
It can be used later by the program that made the function call.

Angie Liceth Pinillos Rodgers


Electronic Engineer
Specialist in Pedagogy for the Development of Autonomous Learning
SENA Instructor
45

Arguments and Parameters: The input arguments of a function can be


passed through two forms: by position or by name.

By position is the typical way values are assigned to a function and consists of
in placing the input parameters in the same order in which they were defined
inside the function:

The sum is 5. In the previous example, a = -3 and b = 8.

The named call consists of calling the function by specifying the name of
input parameter that we are assigning within the function:

the remainder is 11

We are going to create a GPIO configuration function and instead of configuring the
GPIO in the main function, we simply write the instructions for
configuration in the created function.

Angie Liceth Pinillos Rodgers


Electronic Engineer
Specialist in Pedagogy for the Development of Autonomous Learning
SENA Instructor
46

With the subfunctions, we are organizing our program.

Now we will create a subfunction that executes the GPIO verification.

And now we call it, and our code looks more elegant.

Angie Liceth Pinillos Rodgers


Electronic Engineer
Specialist in Pedagogy for the Development of Autonomous Learning
SENA Instructor
47

5.4. USING LISTS IN PYTHON


Lists in Python are variables that store 'arrays', objects, where
Internally, each position can be a different type of data.

In other words, a list is a compilation of arbitrary objects, similar to arrays in


many other programming languages, but more flexible. The creation of a list
it is done using square brackets [ ] and separating each object with a comma ( , )

empty_list = []
languages = [‘Python’,‘Ruby’,‘Javascript’]
fibonacci = [0, 1, 1, 2, 3, 5, 8, 13]
data = [‘Tenerife’, {‘cielo’:‘limpio’,‘temp’: 24}, 3718, (28.2933947, -16.5226597)]

The lists are sorted: A list is not just an arrangement of several objects. It is
an ordered collection of objects. That is, the first element will start
always with the zero (0) index or address, the second element with 1 and so on
successively.

5.5. USING for IN PYTHON


The structure of the for loop is simple. The first line identifies the loop and defines a
index, which is a number that changes at each step through the loop. After
the command group that is to be executed in a way comes from the identification line
IDENTADA.

Angie Liceth Pinillos Rodgers


Electronic Engineer
Specialist in Pedagogy for the Development of Autonomous Learning
SENA Instructor
48

Function range(): The Python function range() is very useful mainly when
we use for loops in our codes since this function returns a sequence
of numbers, starting from 0 by default, increases by 1 (of
default form) and stops before a specified number, that is the
The last number is not inclusive.

As an example, we use the following for loop in Python to create a


sequence of numbers from 0 to 100 and print each element in the sequence:

The syntax of the range function is:

range(start, stop, step)

start is the number where the sequence begins, stop is where the sequence ends
arrives without including that number and step indicates how often it increases the
sequence.

Let's look at the following example with a for loop in Python showing a sequence of
números de 10 hasta 1000 con incrementos de 10 en 10.

5.6. USING if-else IN PYTHON


One of the most common conditionals is the one used by the statement if, which
presents the following structure:

Angie Liceth Pinillos Rodgers


Electronic Engineer
Specialist in Pedagogy for the Development of Autonomous Learning
SENA Instructor
49

If the comparison (a logical expression) is true, the commands are executed.


between the if block, that is, everything that is indented after the condition.
If the comparison is false, the program immediately jumps to the statement that does not
it is indented.

Indentation: In Python, indentation is very important, as it allows for


they establish code blocks belonging to a certain functionality
within the programming language.

In this case, we are seeing how with indentation we are defining


a code block exclusive for the if conditional.

If we want to return to the main code block, we must unindent and go back to the
same line as the main one. That is why Python is a programming language
extremely organized and easy to read, as the language itself forces us to be so.

Indentation can be done with the tab key or with the spacebar. If you
It is standard to use 4 spaces for indentation with the space bar.
indentation, although this is not mandatory.

Always remember to use the same number of spaces throughout your code, if you wish.
use the space bar to indent.

If/else conditional in Python

The else clause allows you to execute a set of statements if the comparison is
true and a different set of statements if the comparison is false.

Nested conditionals in Python (elif)

When multiple levels of if/else statements are nested, it can be difficult to determine
which logical expressions must be true (or false) in order to execute
each set of statements. The elif function allows you to check multiple criteria
while keeping the code easy to read.

Angie Liceth Pinillos Rodgers


Electronic Engineer
Specialist in Pedagogy for the Development of Autonomous Learning
SENA Instructor
50

[Link] while EN PYTHON


While loops are similar to for loops which are used to repeat a block of
Instructions within our program, the big difference with the FOR is the way
in which PYTHON decides how many times to repeat the loop. While loops continue
until some criterion is met.

What is the structure of the while loop?

The structure of the while loop must adhere to the following syntax, which always in
Python must respect indentation, since once the indentation goes back to
the same line of the while command, this indicates the end of the While loop to Python.

Below is an example of the use of the while loop which contains a


accumulator number that will keep increasing until the accumulated sum is greater
that 100

Angie Liceth Pinillos Rodgers


Electronic Engineer
Specialist in Pedagogy for the Development of Autonomous Learning
SENA Instructor
51

6. PROJECTS WITH DIPSWITCHES AND LEDS


WITH THE RASPBERRY PI 4B
Dipswitch: a set of electrical switches that comes in a format
encapsulated. This type of switch is designed to be used in a similar panel.
to the printed circuit board along with other electronic components and is used
commonly to modify or customize the hardware behavior of
an electronic device in certain specific situations. DIP switches are
always lever-type switches, in which the central ones have two positions
possible "ON" or "OFF" (instead of by intervals) and generally, you can see the.
numbers 1 and 0.

The correct way to connect the dipswitches is with Pull-Up resistors.

VDD

R9R1R01R11R21R31R41R516

PB7
PB6
PB5
PB4
PB3
PB2
PB1
PB0

DSW1
DIPSW_8

In this way, the input of the Raspberry Pi 4B is always receiving a '1'.


when the dipswitch is up and a '0' when the switch is down
down.

Angie Liceth Pinillos Rodgers


Electronic Engineering
Specialist in Pedagogy for the Development of Autonomous Learning
SENA Instructor
52

LEDs: electronic device that emits light. It is used to visualize presence of


current, to show whether an output is at '1' or at '0'.

The correct way to connect an LED to the Raspberry Pi 4B is:

R8
150R

D8
LED-GREEN

For our projects with DipSwitch and Leds with the Raspberry Pi 4B, we will rely on
in the schematic circuit.

Placing the components on the breadboard

Angie Liceth Pinillos Rodgers


Electronic Engineer
Specialist in Pedagogy for the Development of Autonomous Learning
SENA Instructor
53

[Link] THE DATA READ BY THE DIPSWITCH V1 ON THE LEDS


The program we are going to implement is to read the GPIO configured as
inputs and display their status on the GPIO configured as output taking into account
this relationship

Bit 7 6 5 4 3 2 1 0
[Link] 19 13 6 5 22 27 17 4
[Link] 21 20 16 12 25 24 23 18

As described earlier, the first step is to import the libraries that are
they need

We create the main function

We set the GPIO library to board mode.

Angie Liceth Pinillos Rodgers


Electronic Engineer
Specialist in Pedagogy for the Development of Autonomous Learning
SENA instructor
54

We configure the GPIO as inputs or outputs

We start the infinite cycle

We use the if-else conditional to check the status of the input GPIO, if the
GPIO is in HIGH state, we write a HIGH to the output GPIO, if the state of the
GPIO is in LOW state, we write a LOW to the output GPIO, we will guide ourselves
from the following flowchart.

Angie Liceth Pinillos Rodgers


Electronic Engineer
Specialist in Pedagogy for the Development of Autonomous Learning
SENA Instructor
55

Inicio
1

Configure GPIO as inputs YES


or output according to the diagram GPIO6 = 1? GPIO16 = 1
NO
SI
GPIO4 = 1? GPIO16 = 0
GPIO18 = 1

NO
YES
Is GPIO13 = 1? GPIO20 = 1
GPIO18 = 0

NO
YES
GPIO20 = 0
Is GPIO17 = 1? GPIO23 =

NO YES
Is GPIO19 = 1? GPIO21 = 1
GPIO23 = 0
NO

YES GPIO21 = 0
Is GPIO27 = 1? GPIO24 = 1
NO
END
GPIO24 = 0

YES
Is GPIO22 = 1? GPIO25 = 1

NO

GPIO25 = 0

YES
Is GPIO5 = 1? GPIO12 = 1

NO

GPIO12 = 0

Angie Liceth Pinillos Rodgers


Electronic Engineer
Specialist in Pedagogy
1 for the Development of Autonomous Learning
SENA Instructor
56

Our code would be:

[Link] THE DATA READ BY THE DIPSWITCH V2 ON THE LEDS


Now we will make use of functions to structure our program. We create
a function to configure the output GPIO, a function to configure the GPIO
an entry point and a function that executes the main code.

Angie Liceth Pinillos Rodgers


Electronic Engineer
Specialist in Pedagogy for the Development of Autonomous Learning
SENA Instructor
57

Angie Liceth Pinillos Rodgers


Electronic Engineer
Specialist in Pedagogy for the Development of Autonomous Learning
SENA Instructor
58

In our main function we call the created functions.

Angie Liceth Pinillos Rodgers


Electronic Engineer
Specialist in Pedagogy for the Development of Autonomous Learning
SENA Instructor
59

[Link] THE DATA READ BY THE DIPSWITCH V3 ON THE LEDS


Now we will add parameters to the created functions, this way we can
configure the pins we need from the function call

Our main function remains:

Angie Liceth Pinillos Rodgers


Electronic Engineer
Specialist in Pedagogy for the Development of Autonomous Learning
SENA Instructor
60

[Link] THE DATA READ BY THE DIPSWITCH V4 ON THE LEDS


In this new version, we will create a list to store the GPIO that will be
set as output, another list to store the GFPIOs that are going to be configured
as an appetizer.

In the functions created we must to use the instruction


list_name.insert(position, parameter) to store the GPIO in the lists

Angie Liceth Pinillos Rodgers


Electronic Engineer
Specialist in Pedagogy for the Development of Autonomous Learning
SENA Instructor
61

Our functions run_codigo() and main() remain the same.

[Link] THE DATA READ BY THE DIPSWITCH V5 ON THE LEDS


Having the GPIO stored in lists, we can use the for function for the
optimizing the code.

Angie Liceth Pinillos Rodgers


Electronic Engineer
Specialist in Pedagogy for the Development of Autonomous Learning
SENA Instructor
62

Now we can use a for loop to optimize the main code.

Our main code remains unchanged

6.6 WRITE TO THE LEDS THE DATA READ BY THE DIPSWITCH V6


In the configuration functions, we will create a Tuple to configure the
GPIO with a for loop. In the Tuple we will store the parameters received by the
functions. In this way we can reduce our code

Angie Liceth Pinillos Rodgers


Electronic Engineer
Specialist in Pedagogy for the Development of Autonomous Learning
SENA Instructor
63

The functions run_codigo and main remain unchanged.

Angie Liceth Pinillos Rodgers


Electronic Engineer
Specialist in Pedagogy for the Development of Autonomous Learning
SENA Instructor
64

6.7 WRITE ON THE LEDS THE DATA READ BY THE DIPSWITCH V7

Now we will create another list to store the states of the input GPIOs and of
output, this in order to create a function that reads all the bits of the GPIO
input and write to all output bits

We create a function that allows us to write all the bits to the output GPIO.

We create a function that allows us to read all the bits of the input GPIO.

And our main code reduces to a single instruction:

Angie Liceth Pinillos Rodgers


Electronic Engineer
Specialist in Pedagogy for the Development of Autonomous Learning
SENA Instructor
65

The complete code would be:

Angie Liceth Pinillos Rodgers


Electronic Engineer
Specialist in Pedagogy for the Development of Autonomous Learning
SENA Instructor
66

Angie Liceth Pinillos Rodgers


Electronic Engineer
Specialist in Pedagogy for the Development of Autonomous Learning
SENA Instructor
67

Fall of part of the reader to pass the created functions to a library, which is not
object of explanation in this book.

With the library, the program could look like this

Angie Liceth Pinillos Rodgers


Electronic Engineer
Specialist in Pedagogy for the Development of Autonomous Learning
SENA Instructor
68

Angie Liceth Pinillos Rodgers


Electronic Engineer
Specialist in Pedagogy for the Development of Autonomous Learning
SENA Instructor
69

Angie Liceth Pinillos Rodgers


Electronic Engineer
Specialist in Pedagogy for the Development of Autonomous Learning
SENA Instructor

You might also like