Introduction: Raspberry Pi Basics

Nowadays electronics, automation, IoT, DIY and robotics are big things. Everybody talk about them and they are in the media everywhere. You don't believe me. Well, just look where you are right now and what are you doing.

Reasons for that are the availability of cheap devices and components, which are very easy to use. Even when there is a lot of engineering work behind those devices and components, their interfaces design makes them very easy to interact with and the learning curve is not too demanding.

Despite that, here are still some basics that one should learn to start creating amazing things. Those basics could seem intimidating for someone with little experience with computers or electronics. Even for those with some experience in one of the fields, the other can demonstrate to be a challenge.

That was my case: I know a bit about computers, but was never too good at electronics. Some weeks ago, I decided to start a project involving a big number of those technologies I mentioned above and felt myself intimidated by the huge amount of possibilities and options, and their potential power.

Then I thought that the best approach would be to start little by little, one step after the other. As I was documenting it for my own reference, I felt that my documentation could be helpful to others, so here I am sharing it with you.

In this instructable I will try to explain you some of the basics I have learnt during these weeks, mainly on Raspberry Pi, GPIO, sensors, python and some other things that allow you to introduce yourself in the world of automation, IoT, robotics, sensors and use them in your projects.

I will try to remove as much complexity as possible, explaining things in plain language and without digging into the technical details. I will try also to provide links and references, for those of you that feel like understanding how all that works under the shell.

Finally, there is something you need clear in your mind: this instructable is not about goals, but about means. What you will learn here are some of the means and tools that will allow you to do great things.

One last thing. I will be using fritzing to do the diagrams and show you how things are connected. If you feel like experimenting with this software, you can download it free from here: http://fritzing.org/.

Another lastest thing. I'm taking part in three contests with this instructable. In particular the one for first time authors, the one for Raspberry and the one for LEDs. If the instructable helped you in anyway, you liked it, you liked me or if you have any other reason, you are more than welcome to show me some love by voting for it. Thanks in advance!!

Step 1: Required Materials

In this instructable I am using a number of components, materials or things (call them as you want).

Some of them are required, while others are optional. Some of them can be replaced by slightly different things, or even by completely different things. In fact, that is what I would expect: that when you finish the instructable you find yourself replacing component X with component Y, which is completely different but is what you need for your very own personal project. That would mean you understand the fundamentals and are ready to fly alone.

I am including links to online shops where you can buy the components. I am in no way affiliated with any of those and do not recommend them at all. Those are only randomly chosen links to show you what I mean with each item and to give you an idea on the cost.

Here is the list of things you are going to need:

A Raspberry Pi with a power supply

https://www.raspberrypi.org/products/raspberry-pi-3-model-b/

https://www.raspberrypi.org/products/raspberry-pi-universal-power-supply/

Those are mandatory. Required. Needed. After all, this is a Raspberry Pi instructable, isn't it?

A micro SD card

https://www.amazon.com/Sandisk-MicroSDHC-Memory-Card-Adapter/dp/B000WH6H1M

At least 8GB. 4GB would be enough, but with 8GB you will play safe.

A computer, with a micro SD card reader and Wi-Fi internet access

Well, no link for those. Really.

I will be using a Windows 10 computer, so the instructions will be based on that. I will provide links with instructions for Linux, if you are one of those Linux users. I could even provide links for the apple fans...

The internet access could be wired, but it will be better to have it wireless. Let's remove as many cables as possible!

A USB Keyboard, HDMI display and HDMI cable

No link neither for those. No link. Seriously.

In fact, you don't really need those. Only in case something goes wrong you could eventually need them, or if you want to connect directly to the Raspberry Pi console, instead of doing it wirelessly. Just keep them at hand.

An electronics development breadboard

https://www.adafruit.com/product/239

The bigger the better, but you don't actually need a full one here. You could even skip it and connect the components without it. A development breadboard just makes connecting everything easier.

A lot of jumper and extension wires (not really a lot, just some)

https://www.adafruit.com/product/758

https://www.adafruit.com/product/826

You will need female/male (extension) and male/male (jumper), in different lengths.

Some colourful shiny bright LEDs

Well, you will need at least one. A basic red one will do it. However, everybody knows how it goes with the shiny lights: you never have enough, and if they blink... well, you know...

Some resistors (as many as LEDs)

Around 1K Ohm are fine. We will be using them to avoid burning the LEDs. (They don't need to be that exact value)

Step 2: What Is a Raspberry Pi?

Raspberry Pi is a single board computer (SBC).

What?

A single board computer, a completely functional computer implemented on a single circuit board.

There are several models of Raspberry Pi (A, B, Compute Module and Zero), and each model has seen different generations.

The model basically defines the form factor of the circuit board and its connectors, including the GPIO connector.

The generation determines other features, such as the processor, the amount of memory or the availability of Wi-Fi or Bluetooth connectivity.

Most current models and generations are:

Raspberry Pi 3 Model B

Raspberry Pi Zero W

The first being more powerful in terms of processing power and RAM, but the second being smaller, cheaper and consuming less power.

If you have the curiosity, you can learn a lot about Raspberry Pi or the specifics of each model and generation in the Raspberry Pi Wikipedia page (https://en.wikipedia.org/wiki/Raspberry_Pi/).

Which one should I buy/use/get?

For the purpose of this instructable, you can use any of them. The only thing you have to consider is that Generation 1 Models A and B have a 26 pin GPIO, while all the others have 40 pin GPIO. Not a big issue here.

I would also advise you to use a model with embedded Wi-Fi module, that's the Raspberry Pi 3 Model B or the Zero W. That makes communicating with the Raspberry easier. However, if you have an old model catching dust, use it.

Well, now that the mystery of Raspberry Pi has been unveiled (yes, it's simply a small computer) we can continue.

Step 3: What Is the GPIO?

GPIO stands for General Purpose Input/Output.

Yeah. But, what does that mean?

It means it is a connector that can be used to communicate with the Raspberry Pi.

The General Purpose part means that it is not designed for any specific purpose, such as an Ethernet port or an HDMI connector, which are designed for a specific functionality. The GPIO can be used for anything and everything.

That has advantages and disadvantages. The main advantage is its flexibility and the myriad of customization options that a GPIO port offer. However, that flexibility comes at a cost, and the costs here are the performance and the usability.

As the GPIO port has not been designed to fulfil a specific function, it is not especially good for anything. HDMI, for example, is designed to perform as much as possible in multimedia (audio and video) transmission. Multimedia signals have very specific characteristics, and HDMI has been tweaked to accommodate those to the perfection. On a GPIO port you could do multimedia transmissions, but they won't be as performant, good or easy as with an HDMI port.

And that easiness is the second cost: the usability. Most of the things you are going to send/receive over a GPIO port are going to be raw electrical signals. There will not be an interface or an API (Application Programing Interface) that will allow you to easily visualize what that electrical signal means. You will have to walk your way through it.

That is what we are learning here. How to use the GPIO and understand the meaning of the different electronic signals through it.

The Input/Output part of the name means that communication is bidirectional: the Raspberry can send and receive information through the GPIO.

NOTE: Many other devices have GPIO ports. Do never assume the pin layout is the same than in a Raspberry, even if the connector looks exactly the same. Go to the documentation and learn what each pin is for. If you don't do that you could end up connecting things wrongly, which could cause damages to the components or, in worst case, even start a fire. You have been warned.

Where is it? How does it look like?

The GPIO looks like two stripes of 20 pins (that's 40 pins, yes).

Pin 1 is the pin closer to the SD card slot (on the bottom side of the Raspberry Pi) and is usually considered to be the top-left pin. The top-right is pin 2, and then next row are 3 and 4 and so on. That is: numbering follows the rows.

In the pictures above you can see a diagram of the board with the pins. Pin 1 is the one in yellow colour, and pin 2 is the one on its top.

When you want something to communicate with the Raspberry Pi, you will connect it those pins.

Some of those pins also provide power that can be used to energize different things. The voltage provided is 3.3V and 5V, so good enough for many things, such as sensors, antennas, displays, etc...

In the diagram you can see each pin in the header and it's function.

So now you now what are those pins and what are they used for. Let's continue the exploration.

Step 4: What Is Raspbian and How Do I Install It?

This is getting interesting. "How do I install it?" meaning that here we will begin to do things and it won't be any more me writing and you reading. Nice.

Raspbian. Well, I said before that the Raspberry Pi was a computer, didn't I? Yes. So, the Raspberry Pi, as any other computer needs an operating system to allow you to interface with it and use it.

That is what Raspbian is: an operating system for your Raspberry Pi, just as Windows 10 or Ubuntu Linux or macOS are operating systems for other computers you could have.

There are many other operating systems for Raspberry Pi, including different distribution of Linux and release of Windows specifically designed for IoT devices. Some of them are general-purpose operating systems, and others are customized to better serve a specific purpose (i.e. to convert your Raspberry Pi in a media centre, a MAME console or a weather station).

If you are curious about those possibilities, you can find details on them here: https://www.raspberrypi.org/downloads/

For the purpose of our instructable we will stick to Raspbian.

Raspbian is the contraction of Raspberry and Debian, so it is a Linux Debian distribution customized for Raspberry Pi.

If you are familiar with Linux in general or with Debian in particular, you will find that the Raspberry Pi, once Raspbian has been installed, behaves as any other computer.

Raspbian has two tastes: Desktop and Lite.

The Desktop edition includes the Pixel desktop environment (a windows based interface, such as gnome or KDE), a lot of software preinstalled and is bigger in size than the Lite version.

The Lite edition is the bare minimum, with the basics to get you up and running.

As the purpose of this instructable is to explore and learn, we are going to use the Lite one and find our way around.

At the time of writing this instructable (around December 2017), the stable version of Raspbian was called Stretch, from November 2017 and with a kernel version 4.9. Those are only random details that if you are not really into Linux will be completely useless for you. But, on the other hand, what would we be without tons of useless information and details?

Where do I get my Raspbian Stretch Lite?

Yeah. Stop the nonsense talk and let's go to the real thing.

You can download both editions of Raspbian Stretch from here: https://www.raspberrypi.org/downloads/raspbian/

Download the Lite edition as a torrent or as a zip, and save it in your computer (I told you we would need a computer).

Once downloaded you will have a .zip file that you will need to extract. To do that you can use 7-zip (http://www.7-zip.org/). That will result in an .img file, which is the image file for the Raspbian operating system.

How do I install Raspbian in my Raspberry Pi?

That's a piece of cake.

Raspberry Pi computers use a micro SD card as storage. You only need to flash the Raspbian image to your micro SD (yes, I told you that you will need one).

To do so you can use Win32 Disk Imager, which can be downloaded from here http://sourceforge.net/projects/win32diskimager/.

Once you have downloaded and installed Win32 Disk Imager, run it.

You will have to select the image of Raspbian.

Then insert the micro SD card in your reader (yes, I told you will need one) and select it in the Device drop down list.

NOTE: Make sure and double-check (even triple-check) that you have selected the right device, as this will delete any content on the selected device and overwrite it with the Raspbian image. You could easily end up with your mobile phone storage having a nice but useless Raspbian image, instead of your music and pictures. You've been warned.

When you are absolutely sure that you have the right micro SD card in your computer, and that you have selected it in the Device dropdown list, click on the Write button.

It will take a few seconds and you will have a nice micro SD with a Raspbian Stretch Lite installation.

Easy, isn't it?

How do I configure my Raspberry Pi with that Raspbian I have in the micro SD card?

Now you could use a monitor connected to an HDMI port of the Raspberry Pi and a keyboard, power the Raspberry and follow the setup wizard. You could insert the micro SD card in the Raspberry Pi and power it on. Then follow the on-screen instructions and you will be done. That would be the easy way. But we don't like the easy things, do we? Let's do it without monitor and without keyboard.

NOTE: Linux is a case-sensitive operating system, in general. Therefore, the file ssh is not the same than the file Ssh. Same applies to folders and usernames. You've been warned.

First thing you need to do is to configure the Wi-Fi connection.

To do so you need to find a file in the micro SD card called wpa_supplicant.conf. It is located in the /etc/wpa_supplicant/ folder.

Edit it with notepad and add a line like this:

network={ssid="YOUR WIFI SSID HERE" psk="YOUR WIFI PASSPHRASE HERE"}

Obviously, you need to replace the placeholders in the code with your actual Wi-Fi name and the password. Keep them between the double quotes.

Save the file and close it.

Then find a file called interfaces in the folder /etc/network/interfaces/.

Find all entries for manual and replace them with dhcp.

Save the file and close it.

What you have just done is to configure Raspbian to connect to your Wi-Fi network and receive an automatic IP configuration from your router.

Next thing is to activate the Secure Shell. Secure Shell (a.k.a. ssh) is a service that allow remote connections to a terminal console. That means that one it is enabled you can open a terminal console in your Raspberry Pi from a different computer connected to the same network.

To do this you only have to create an empty text file called ssh in the boot partition of the micro SD card. Really easy.

So, that is the basic configuration.

Now remove the micro SD from your computer, put it on your Raspberry Pi and power it on with the microUSB power adapter.

A red led shall light on, which is a good thing.

How do I connect to my Raspberry Pi?

Well, now you have a Raspberry Pi running the Raspbian Stretch Lite operating system and connected to your Wi-Fi network.

That's somehow great, isn't it?

But the beauty of it is in connecting to the machine and being able to do things with it. If not it's only a circuit with a led consuming electricity. Not very useful.

To connect to it, you need first to know its address.

When you connect a device (any device, a laptop, a phone, a Raspberry Pi...) to a network (wireless or wired) it gets assigned an IP address. In fact, anything connected to the internet (which is a network) has an IP address. IP stands for Internet Protocol.

That IP address is allocated by the router (the device that connects you to the Internet) and is randomly chosen from a pool of available addresses.

We will be using a tool called Angry IP Scanner. You can download it from here: http://angryip.org/download/.

The tool will allow you to scan your network to find the IP address in your network that are used by devices.

Run the program and it will automatically detect the network range you are connected to. Click on the Start button and in a few seconds you will see a message informing you that the scan has completed and a list of IP addresses with red dots for those IP addresses not in use (or not detectable by the scan) and blue dots for those IP addresses in use.

The default hostname assigned by Raspbian to any Raspberry Pi is rasbperrypi, so find it in the list and you will know what is the IP address that it has been allocated. In my case, my Raspberry Pi has the IP address 192.168.1.220.

Now, to connect to that IP address you need a terminal program that allows SSH connections. One of the most popular is PuTTY, which you can download from here https://www.chiark.greenend.org.uk/~sgtatham/putty/latest.html. Download and install it.

Once it is installed run it and in the Hostname (or IP address) textbox type the IP address of your Raspberry Pi. Make sure that the port is 22 and the connection type is SSH, then click on Open and the magic will happen!

Oh... wait... hold on. A security alert pop-up!

The text in that alert means: guy you are connecting to something that does not have a digital certificate or anything similar. I cannot guarantee that it is what you think it is. Do it at your own risk.

Well, if you are not connected to the internet, you have the Raspberry Pi connected in your network, there are not more Raspberry's there... you can be quite positive about it being your Raspberry Pi.

There are still a lot of checks and things you could do to confirm that point, but they completely fall out the scope of this instructable, so click Yes and let's continue.

Once you click Yes you will be presented a terminal console with a login prompt (yes, that black screen with letters is a terminal console). Just login using the default username (pi) and the default password (raspberry).

You are now connected to your Raspberry Pi!! Congratulations!!

First things first. A basic command:

To end your session and logout use this:

logout

How do I further configure my Raspberry Pi?

Well. Raspberry Pi and Raspbian offer a myriad of possible configurations and customizations. Literally. As any other computer.

Raspbian makes it easy for us to configure the basic ones by offering us the raspi-config program. This program offers us an interface with the most usual settings to configure.

Open the program by executing this command:

sudo raspi-config

Wait a minute. I am asked for a password. What is that?

That is what happens when you run a program (raspi-config) in with elevated rights (sudo). sudo is a command that tells the computer "run this program as super-user", that is with all the available privileges and rights. That's why you are asked for a password, to ensure that you are authorized to run raspi-config.

If you would run raspi-config without the sudo context, raspi-config will not have the privileges to do the required changes in the system configuration and will get plenty of access denied errors.

Now that you know why, you can put the password of the pi user (raspberry) and continue. You will see a lovely blue screen with a grey menu on top of it.

Now I am going to tell you the things that you need to configure and give you some details. If you are curious about the rest of them, you can find details on each option here https://www.raspberrypi.org/documentation/configuration/raspi-config.md.

The most relevant options for you at this moment are:

1. Change user password. Just do it. I don't think there is a need to explain the why.

2. Hostname. Well. Maybe you will find more comfortable a different name, but it does not really matter.

4. Localisation options. Here you can change your locale, time zone and Wi-Fi country code.

7. Advanced Options > A1. Expand file system. This option will allow you to use all the micro SD card available space.

Once you are done, select the Finish option. Depending on the settings you changed, you could be offered to reboot the Raspberry, as the settings won't be active until that moment. DO NOT REBOOT NOW. There is still something to do.

How do I fix my IP address?

As I told you before, the IP address of your Raspberry Pi is assigned randomly by the router. This is very convenient, as it allows for automatic configuration, but on the other hand makes it a pain to connect to your device, as on each reboot the IP address could change and you will have to go through the Angry IP Scanner process again. Painful... very painful... (Yes, I'm that lazy).

There are two ways to solve this:



Setting up a DHCP reservation in your router.

Manually configuring the IP address in your Raspberry Pi.



Fact is that, even when both methods are good and you could also combine both of them together, it is very difficult to write detailed instructions, fail-safe, here. With that in mind, I will provide you with some guidelines and you have to promise that you will investigate further and do it properly.

Promise it...

I'm waiting...

Well done.

Now, method 1. depends basically on your router. You need to access the administration or management interface of your router, find the DHCP section and options related to the reservations, fixed leases or something similar. If you have been provided your router by your Internet Service Provider (ISP) you will have to ask him or to google how to access the admin area and find that configuration section. Most probably, it will be under the advanced settings.

There you will map an IP address to a MAC address (which is a fixed, hard-coded, address for your network adapter). This will tell the router: whenever this MAC address asks for an IP address don't give it a random one, give it this specific one.

As the IP address you can chose the one you have right now.

To know what the MAC address is of your Wi-Fi network, type this command in your terminal:

ifconfig wlan0

That will give you a lot of details of your current configuration, such as the IP address (following the inet keyword), the IPv6 address (if any, following the inet6 keyword) or the MAC address (after the ether keyword).

Just take note of the inet and the ether to use them in the DHCP lease reservation on your router.

After that, each time you reboot your Raspberry Pi you will be assigned the same IP address and you will not have to go through the Angry IP Scanner process.

Method 2. consists in telling your Raspberry Pi: ey, don't use the automatic IP address configuration provided by the router. I will just set it manually.

That's perfectly fine. Well, almost perfectly fine. It has an issue: you are not telling the router that you are going to use a specific IP address always without consulting with him. So it could happen that at a given moment the router gives your IP address to another device (your phone, your tablet, your laptop...) and that will create an IP address conflict, where the router will not know to whom send the packets addressed to that IP: to your Raspberry or to the other device.

To avoid that you need to know what is the range of IP addresses that the router is configured to lease, so you can configure an IP that is not in that range. For that, you need to access your router, asking your ISP or checking out the router documentation. However, if you reach that far, then you should be able to implement method 1, which is easier and better.

So, to summarize, there are 3 ways to access your Raspberry Pi:



Use the Angry IP Scanner to know the current IP address and connect to it using PuTTY.

Set up a DHCP reservation on your router, so your Raspberry Pi is always assigned the same IP address.

Manually set up a fixed IP address to your Raspberry Pi, which should be out of the DHCP lease range of your router.



As method 3 is more complex than method 2, I will suppress it from the list: you have method 1 and 2. That's it. Your choice.

More things you need to do: updating your firmware

It is always a good idea to have your firmware updated. Well... not yours... your Raspberry Pi's firmware.

Run this command to do so:

sudo rpi-update

It will take a few minutes to have it done and the Raspberry Pi will need a reboot to apply the changes. You will learn now how to reboot the Raspberry Pi.

Tell me another command!! I like those!!

Ok.

Most probably, you want to know how to shut down or reboot the Raspberry Pi.

There are 2 ways:



You just remove the power with your fingers tightly crossed and telling your prayers so no file gets corrupted and your system destroyed.

You use the shutdown command.



To shut down your Raspberry Pi just type:

sudo shutdown -t now

To reboot your Raspberry Pi just type:

sudo shutdown -r -t now

If you replace now with a number, the command will wait that number of seconds before executing.

Next step is the last one before starting the fun part. Well, all this is also fun, but you know what I mean.

Step 5: What Is Python and How Do I Install It?

Python is a high-level general-purpose programming language.

There we go again. What?

Python is a programming language, so it allow us to encode sequences of commands to instruct a computer to do something. Those sequences of commands can include logical comparisons and evaluations, which will allow the computer to take decisions based on certain criteria.

For example, you can program your computer to ask you for a number from 0 to 9. Then you can instruct it to power a green led if the number is higher than 4 or a red one if the number is lower or equal to 4.

That would be a program, and could be encoded using Python programming language.

General-purpose, as the GPIO, Python is not optimized for any specific application. Can be used for anything and everything. On the other side, there are purpose specific programming languages, which are designed to perform better in complex mathematical calculations, artificial intelligence applications or other areas.

And high-level? Something like "top-of-the-crop"? Not really that. No.

A computer is basically a set of electric circuits. Working directly with electricity is a mess, and even more at the level that is done in a modern computer: micro voltages, with micro components and microcircuits, processing things at the speed of light (literally in some cases). Impossible to work with directly. Trust me.

What some super-smart engineers do is to convert that electricity in things more easily usable. The electricity is first converted to values, most often binary values. That's 0s and 1s. So when there a circuit is powered we will say it is a 1 and when it is not powered we will say it is a 0. This is the first level of abstraction.

Of course, programing a computer like that is crazy (not impossible, only crazy), so the engineers begin to group combinations of those 0s and 1s in things that make more sense to humans. So they encode letters and digits with those combinations and develop programs that interface from those letters and digits to electricity and vice versa.

That way, the computer uses electricity (which is what the machine understands) and the human in front of it uses complex symbols that are meaningful to him.

Those letters and digits are again grouped and combined, forming words, commands, instructions... then those again into more complex things.... reaching even the level of graphical interfaces or gestures recognition.

So, you can imagine a line with the electricity on the left end and the most modern interfaces you can imagine on the right side. The more to the left you are, the closer to the machine "language" you are... the closer to the right the closer you will be to humans "natural" languages.

With that in mind, "low-level" things in the world of computing are things close to the machine side, while "high-level" things are those closer to the human side.

When we say that Python is a high-level programming language, what we mean is that it is closer to the human natural language, so you will easily understand the program code and see what it does.

High-level things have the advantage of being more easy to use and more intuitive for humans, while low-level things are very, very difficult to understand for a human.

On the other hand, low-level things require less interpretation and abstraction layers to be understood by the machine, so usually are more powerful and performant than high-level ones, which have to go through interpreters, compilers, hardware abstraction layers and other transformation elements before they are understood by the computer.

So, being high-level, Python should be easy, isn't that? Yes, it's very easy. A piece of cake.

Preparing the Raspberry to install Python

As we have seen, the operating system on your Raspberry Pi is Raspbian, a taste of Linux Debian.

Debian has a software packages manager called apt. It allows you to manage the software packages managed on your system. That is, install software, update it and remove it.

apt has a file with a list of software repositories. Those repositories is where the apt goes to find the software you ask, and any other software that could be required to install yours.

It also allows you to update the operating system, and that is the first thing we are going to do.

You need to execute these commands (in any of them you could be asked for a confirmation. Just confirm by pressing Y):

sudo apt-get update

apt-get update finds your repositories sources list and contacts each repository for an updated list of the software and versions available.

sudo apt-get upgrade

apt-get upgrade compares the software installed in your computer with the latest information available from the repositories and lets you know which updates are available. Then, if you feel so, you can update those software packages by answering Yes when asked.

sudo apt-get clean

apt-get clean find software packages that are obsolete or not needed in your system and removes them. That results in a cleaner, more performant, and better system. That's good.

sudo apt-get dist-upgrade

apt-get dist-upgrade does the same than apt-get upgrade but instead of updating installed software packages, it updates the operating system itself. A good thing to do.

Note that the screenshots here show the outputs of the commands in my Raspberry Pi. On yours, depending on how outdated or updated is your raspbian the output could be slightly different.

Installing Python

Done. Next section.

What? Hold on... done?

Yes. Python is installed by default as part of the Raspbian operating system.

Don’t you trust me? Just check it yourself. Run this command:

python3 --version

It will return the version of Python installed in your system. Mine is 3.5.3.

Installing the GPIO libraries

In order to interact with the GPIO we need to 'extend' Python using libraries.

Libraries are software packages that provide specific functionalities to a programing language as Python.

In particular, the GPIO library allows Python to easily interact with the GPIO port of the Raspberry Pi.

To install it, execute this command:

sudo apt-get install python3-rpi.gpio

Yes, you guessed it: apt-get install allows you to install a software package and any required dependencies.

Installing pip and serial libraries for Python

pip is a software packages manager, similar to apt, but for Python. It allows you to install and manage Python related packages.

To get it installed, run this command:

sudo apt-get install python3-pip

After some seconds, the installation will complete and we will be able to install the serial library for Python.

Those libraries will allow us to use the UART pins in the GPIO as a serial port.

We do it by running this command:

sudo pip3 install pyserial

Once installed you will be good to go. Everything you need is ready.

Hello world!

Well... this is a must.

First program you will program with any given programing language in any platform is going to be a simple code that outputs "Hello world!" in the screen.

If you skip this, you will have 7 years of bad luck. Sorry. That's life.

Luckily, for us, that's very easy to do. Let's do it.

First, confirm you are in your home folder.

In Linux, the home folder is identified by the symbol ~. If you look at the console, you will see that the prompt is something like

pi@raspberrypi:~ $

pi is your username

raspberrypi is the hostname, the name of the computer (maybe you already changed it).

After the colon (:) there is the path to the current folder, which is home in my case (~).

Finally, the $ is the prompt, where you can type commands.

So if you see the ~, then you are at home.

To list the content of your home folder you can use this command:

ls

The ls command will show you the files and folders in the current directory.

If you want extended information, you can use the -la switch in this way:

ls -la

That will give you also information on the permissions for each item, who are the user and group owning the item, the size and the timestamp of creation. Right now, you don't need any of that information.

If you are not in your home folder you can go there using the cd command:

cd ~

If you want to go to any other directory, just use cd with the directory name.

cd /home

If you want to go to the root (/) directory, same thing:

cd /

And if you want to go one level up in the directory tree use 2 points (..):

cd ..

Finally on this, to see the full path of the current directory you can use the following command:

pwd

That's how you navigate the directory structure. Enough of that for the moment.

Now, go to your home directory and create a file called helloworld.py (remember Linux is case sensitive!) by issuing these commands:

cd ~
touch helloworld.py

The touch command creates an empty file. If you execute now the ls command, you will see the file sitting there.

Edit the helloworld.py with the nano text editor by issuing this command:

nano helloworld.py

nano is a very basic and simple text editor, but it's more than we need now.

Write these two lines in the file:

#!/usr/bin/python3
print ("Hello World!");

Press Ctrl+O to save the file. Press Enter to accept the name. Press Ctrl+X to exit nano.

If you execute again the ls command, you will see that the file size has changed.

You have created your first Python program. To run it just execute this command:

python3 ./helloworld.py

If everything goes as expected, you will see in the screen the "Hello World!" message. Wow!! Amazing, isn't it?

The first line of code identifies the name and location of the executable that the system should use to make sense of the code. In our case /usr/bin/python3.

The second line just tells to print in the standard output (your screen, by default) the message in the quotes.

Easy, isn't it? You can try to change the message and experiment with it.

I'm lazy. I don't want to type the 'python3' each time I run the program

Well... if you are that lazy, you would better get a good doctor.

In any case, to avoid typing python3 each time, as the file already includes in the first line the reference to the python3 executable, you only have to convert the file to an 'executable' file.

To do so, execute this command:

chmod +x helloworld.py

After that, you can execute your program just with this:

./helloworld.py

Nice, isn't it?

Deleting my greeting

Yes, I am a poet.

In Linux you delete a file with the rm command. When you get fed up of your helloworld.py thing, run this command to make it disappear:

rm helloworld.py

Now the file is gone. You can confirm it with the ls command.

NOTE: Warning here!! Guy, as you have seen there are no confirmation prompts, no warnings, nothing. Here you delete a file and no questions are asked. That is true for a simple irrelevant file, but also for the most critical folder holding hundreds of your loved pictures or your music collection. To make it even more risky, the rm command supports the use of wildcards, so you can delete all the files and folders there with a simple command, no questions, no witnesses... for sure it will look like and accident... Morale: don't fool around with the rm command. Double-check what you want to delete. You've been warned.

To sudo or not to sudo

As you have seen, for some commands I use the sudo thing and for others I don't.

What's the criteria to use it or not?

Well, the criteria is simple: when you have rights to do your actions, you don't need sudo. When you don't have rights, you use sudo to get them.

As an example, all the configuration files in the system are owned by root, the super user of the system. You can verify that by executing this command:

ls -la /etc

The command above shows the details on the content of the /etc folder, which holds the configuration files in a Linux system.

That is the reason why when you run raspi-config you need to get additional rights: your pi user does not have rights on the files owned by root. When you include the sudo before the raspi-config, you get those rights. Getting those rights is called 'elevation'.

If you run these commands you will create a file in your home called test.txt and then you will show its details.

touch ~/test.txt
ls -la ~

As you can see, that file is owned by you (pi), so you don't need elevation to open it, modify it or delete it.

That's the theory. Now, in practice, how do I use sudo? I use it as a warning.

Normally I run all the commands without sudo.

Those that don't need it I consider them as not dangerous, and that's it. They run. Next command.

For those that need it, if I don't use it, I will get an Access Denied error. I will understand that error as a: "Ey guy!! What you are doing is risky. Are you sure you know what you are doing? Do you really want to do it?"

At that point, I force myself to double-check what I am doing and only provide the sudo command when I'm completely sure that I want to execute it.

Now, go and delete the test.txt file. By now you should know what command you will have to use, and also you should be able to guess if you will need elevation or not. Just think a little bit on it before trying.

Step 6: Hands On!! Controlling a LED (digital Output)

And now, a practical hands-on, absolutely useless example
which will give a taste of the power of all you have just learnt!!!

We are going to…. (Fanfare… drum roll… another fanfare…) switch a LED on and off!!

Wow! Amazing! Yeah!

Really.

What is a LED?

But, hold on… what is a LED?

A led is a Light-Emitting Diode.

Really?

Yes.

Now, seriously, what is a LED?

Ok. A LED is a Light-Emitting Diode.

A diode is an electrical component. The most basic of the semi-conductor components.

Semi-conductors are special materials that in some case isolate electricity and in some others conduct it.

Again?

Yes. In some cases, a semi-conductor will act as conductor, allowing electricity to go through. In other cases, it will act as an insulant and will not allow electricity to go through.

In particular, a diode has two leads: an anode and a cathode.

When electricity flows from the anode to the cathode, the diode allows the flow of electrons.

When electricity flows from the cathode to the anode, the diode does not allow the flow of electrons.

If you are into plumbing, a diode behaves like a no-return valve in a pipe circuit: only allows water flow in a given direction.

That has many different utilities, as it allows controlling the direction of the flow of electricity in a circuit. If you are curious and want to learn more about diodes and their applications in this link you have some basic information: https://en.wikipedia.org/wiki/Diode.

Then a LED is a diode that emits light: when the anode is connected to a power source (V+, VCC) and the cathode is connected to a power sink (V-, GND) the LED will lighten up. If connected the other way around, it will not light up.

A led usually shows like a small plastic bulb (3mm diameter) with 2 metallic connectors, one shorter than the other.

The long terminal is the anode (+) and the short one is the cathode (-), which also shows a cut in the plastic capsule of the bulb (mnemonic: less metal in the terminal or less plastic in the capsule is for the negative terminal which is connected to the V-, the GND or the pole with less electrons. On the other hand, it has the longer name!! Amazing, isn’t it?)

It is also important to highlight that if you don’t want to get your LED burnt you should always put a resistor in line with it in the circuit.

Now the circuit!

Yes, as we said, we are going to have a circuit with a LED, and we are going to control the circuit with the Raspberry.

The basic circuit consist of a power source (a battery or similar), a switch, a resistor and a LED.

The battery powers the circuit. The resistor reduces the amount of power that reaches the LED. The led transforms that power into light. The switch closes or breaks the circuit.

You can see the basic circuit in the first diagram.

But we have a Raspberry Pi, don’t we?

Yes, so we are going to replace the power supply and the switch with the Raspberry Pi, like in the second diagram.

We will use the GPIO23 (pin 16 on the header) of the GPIO as the V+ in the battery and the pin 6 as GND or V- in the battery (you could use any other GND pin).

The logic in the python code will implement the switch, and the connections will be like in the drawing.

What is that code?

Now that you have everything nicely wired, it’s time to code.

Following the instructions in the previous sections, you will create 2 files:

led-on.pyled-off.py

The content of led-on.py is this:

#!/usr/bin/python3

import RPi.GPIO as GPIO # imports GPIO library

GPIO.setmode(GPIO.BCM) # sets the mode of the GPIO to BroadComm

GPIO.setwarnings(False) # suppress the warning about the pin 16 being already used

GPIO.setup(23,GPIO.OUT) # sets the pin 16 in the GPIO as an output pin

print ("LED on") # prints a message in the console

GPIO.output(23,GPIO.HIGH) # sets the signal in GPIO 23 to high power (power on the LED)

The content of led-off.py is this:

#!/usr/bin/python3

import RPi.GPIO as GPIO # imports GPIO library

GPIO.setmode(GPIO.BCM) # sets the mode of the GPIO to BroadComm

GPIO.setwarnings(False) # suppress the warning about the pin 16 being already used

GPIO.setup(23,GPIO.OUT) # sets the pin 16 in the GPIO as an output pin

print ("LED off") # prints a message in the console

GPIO.output(23,GPIO.LOW) # sets the signal in GPIO 23 to low power (power off the LED)

As you can see in the code, there are comments letting you know what each line does.

Now, when you execute each of the commands the led will turn on and off respectively.

And that’s it!! You can switch on and off one LED by running a command.

Not impressed?

Well… switching on and off a LED is not very impressive. Agreed. But what do you tell me about a lamp at your place? Or the heating system? Or anything else? Much better, isn’t it?

Now, just replace the LED with a relay, which will allow you to control alternate 110V/220V devices and appliances… and then you will be rolling.

Happy exploring!!

LED Contest 2017

Participated in the
LED Contest 2017

First Time Author Contest 2018

Participated in the
First Time Author Contest 2018

Raspberry Pi Contest 2017

Participated in the
Raspberry Pi Contest 2017