Raspberry PI and GPIO pins: Controlling a LED with Bash and Python

In the previous post we saw were the GPIO pins and some examples of practical applications, Today we will focus on the operation of general-purpose pins, and learn to control them with the interpreter's orders Bash and with Python.


Will use a LED, a resistance of 330 ohm, wire, and one Breadboard, or solder and a soldering iron.

We will also need our Raspberry have already Raspbian pre-installed, If your case is not, You can see how to do it in the following link from the Directory.

Riding the circuit

You can solder directly the LED wire and resistance as you will see in the following diagram, Although it is much better to use a Breadboard; It is also very important to look well on sideburns, as in the “diagonal” inside of the diode LED combining the two pins to mount the circuit, already that if you mount it backwards will not turn on.

Circuit needed to control the ignition of a LED diode.

Circuit needed to control the power of a LED diode.

I'm going to use one Breadboard, and I recommend that you use a, There are some from approximately €4 and they allow us to reuse components over and over again without having to solder them, the internal connections of one Breadboard they tend to be the following.


A Breadboard connections.

The connections between the Breadboard and the Raspberry they must be as in the following diagram, the GPIO You can reach issue 3,3V to assign a logical high value.

Circuit on Breadboard.

Circuit needed to control the power of a LED diode.

Hello World of the GPIO with Bash

Once mounted circuit, We are going to do what I call a “Hello World GPIO” in Bash running the following script.

#Exportamos el puerto GPIO 17 
echo 17 > /sys/class/gpio/export 
#Lo configuramos como salida 
echo out > /sys/class/gpio/gpio17/direction 
#Encendemos el LED asignandole 1 como valor lógico
echo 1 > /sys/class/gpio/gpio17/value

To turn off the LED, we can do it with the following script.

#Apagamos el LED asignandole 0 como valor lógico
echo 0 > /sys/class/gpio/gpio17/value  
#Eliminamos la entrada del puerto GPIO 17 
echo 17 > /sys/class/gpio/unexport 

Basically what we are doing with Bash is to create a Directory hierarchy in /sys/class/gpio and adding content to each file that will be treated as a variable.


Hierarchy within the /sys/class/gpio directory.

Introduction to Python

We have already proven that our circuit is working correctly and the LED has it been fired to give a logical high value to the variable, Now let's see how we can do the same in Python, that will allow us to schedule our web applications to control the inputs and outputs of the GPIO from any device.


Operation using the WEB application.

Before proceeding, I recommend that you see the chapters of the 1 to the 10 of This video tutorial from Python the channel of YouTube of Code facilitated, If as I do not have much idea of programming in Python, It can come to you very well to familiarize you with the code that we will see more ahead and come to understand it.

Different Pinouts of the GPIO (BCM and Board)

There are two types of pin numbering, the physical numbering or mode BOARD, and the numbering of the chip SoC Broadcom controlling them, We are going to use the pinout in mode BCM, but let's look at the difference.


Hello World of the GPIO with Python

After watching the videos, and different pinouts can already understand the Basic code to make the “Hello World GPIO” in Python.

First we are going to download everything you need to control the GPIO with Python, in Raspbian they are already installed Python and the libraries GPIO, but we are going to install an additional package and update the system to have the latest version.

usuario@maquina:~$ sudo apt-get install python-dev
usuario@maquina:~$ sudo apt-get install python-rpi.gpio
usuario@maquina:~$ sudo apt-get update && sudo apt-get upgrade

Updated once, Let's see how to turn on the LED with the following script, You can for example call enciende.py, and we can run it as root with the command “sudo Python enciende.py”.

#!usr/bin/env/ python
#importamos la libreria GPIO
import RPi.GPIO as GPIO 
#Definimos el modo BCM 
#Ahora definimos el pin GPIO 17 como salida
GPIO.setup(17, GPIO.OUT) 
#Y le damos un valor logico alto para encender el LED
GPIO.output(17, GPIO.HIGH) 

With this we can turn it off, for example call apaga.py

#!usr/bin/env/ python
#importamos la libreria GPIO
import RPi.GPIO as GPIO 
#Definimos el modo BCM
#Ahora definimos el pin GPIO 17 como salida
GPIO.setup(17, GPIO.OUT) 
#Y le damos un valor logico bajo para apagar el LED
GPIO.output(17, GPIO.LOW) 
#Finalmente liberamos todos los pines GPIO, es decir, los desconfiguramos)

And with this we will call you parpadea.py, We will make flashing the LED.

#!usr/bin/env/ python
#importamos la libreria GPIO
import RPi.GPIO as GPIO 
#Importamos la libreria time
import time 
#Definimos el modo BCM 
#Ahora definimos el pin GPIO 17 como salida
GPIO.setup(17, GPIO.OUT) 
#Queremos que lo que contenga el for i in range se repita 5 veces
for i in range(0,5): 
        #Asignamos valor logico alto para encenderlo
               GPIO.output(17, GPIO.HIGH) 
        #Esperamos un segundo
        #Asignamos valor logico bajo para apagarlo
         GPIO.output(17, GPIO.LOW) 
        #Esperamos un segundo
#Una vez termina las 5 repeticiones, liberamos el pin GPIO utilizado; en este caso el 17

If you do not import the library “time“, can not add the “sleep“, and if not add the “sleep” of a second between on and off, It is quite possible that our eye will not perceive flicker.

It is very important not to add special characters in the scripts in Python, for this reason the comments do not carry accents, Since it gave character error invalid.

In the following entry We will see how to make a simple Web application allow us to execute these scripts, to be able to control it from any device with browser Web.

If you like you can follow me on Twitter, Facebook, Google +, LinkedIn, or share it with the buttons under this publication, If you have any questions or suggestions please do not hesitate to comment.

Help us to reach more readers Share on LinkedInShare on FacebookTweet about this on TwitterShare on Google+Email this to someone

16 thoughts on"Raspberry PI and GPIO pins: Controlling a LED with Bash and Python

  1. I have a question from newbie…
    because the resistance of 330 ohm and when to use it?

    Are always used for 330 When we work with RPI, or it may vary?

    A greeting and excellent blog!!!

    • Hi Peter,

      In principle it should work, error has only given permissions to some people but running from the web application, as the user www-data by default no longer has these permissions.

      Just in case try running “sudo chmod + x script.py” to make it executable, Although not so it should work just from terminal; You can teach me if returns you an error in the terminal to run the script??

      Thank you very much for your comment.

  2. Good, When I enter the script in python, tells me that the arroba is a SyntaxError what can be? Thanks and greetings.

  3. Hello,
    I am trying to turn on an LED through python following guide samples but it gives me the following error when I run the code it:

    import RPi.GPIO as GPIO

    -bash: import: the order was not found

    Do you know why this error is?

    Thank you and congratulations on the blog is serving me much!

    • Nano Hello, Thanks for commenting.

      It seems that the code is being interpreted by Bash and not by Python.

      Are you running the script, or the lines of code in the terminal directly?

  4. Good again,
    what I don't understand is the first line of code: #!usr/bin/env/python
    What is it?
    I see that it works just with or without it

    • Nano Hello, welcome again.

      The line you mention is the statement that is often included at the beginning of a script to tell the terminal where the interpreter which orders should you pass, in this case, Python; for bash would be as follows:


      In this case, it works with the Declaration and without it since the file has the extension .py, but it is good practice to always add it.

      I hope to have cleared your doubts, back here whenever you want and thank you very much for your comment 🙂

  5. Thank you, the tutorial is excellent, but I have a doubt:

    they leave me with the following errors:

    line 12 import:not found
    line 14 syntax error: Word unexpected (expecting “)”)

    My code is:

    # Provides: GPIO-setup.ch
    # Required-Start: $remote_fs $syslog
    # Required-Stop: $remote_fs $syslog
    # Default-Start: 2 3 4 5
    # Default-Stop: 0 1 6
    # Short-Description: Setup mode gpio
    # Description: Setup gpio 22/27/17/4 out mode

    import RPi.GPIO as GPIO
    #We define the BCM mode
    GPIO.setmode(GPIO. AC.)
    #Now we define them pin GPIO as output
    GPIO.setup(4, GPIO. OUT)
    GPIO.setup(17, GPIO. OUT)
    GPIO.setup(27, GPIO. OUT)
    GPIO.setup(22, GPIO. OUT)

    Any idea???

    • Hello Leoctam, Thanks for commenting.

      The first lines give to understand that you are trying to create a system daemon, but they are commented so it will not be taken into account.

      On the other hand, the code that you are using to interact with the GPIO is Python, so you must stay in a script .py that will be invoked from your system daemon, or use Bash to do so as in the first example in this tutorial.

Leave a Reply to Nano Cancel reply