Button and LED circuit with the Pi

In the previous post we sent data out the GPIO ports to turn ON/OFF a single LED. In this post we are going to read data from the GPIO (with a push button) and write (send) data out the GPIO (turning ON/OFF the same LED). However before we start let us review a few concepts we need.

Interrupt Service Routine (ISR)

An interrupt service routine (ISR) is as the name suggest a routine (software routine) that respond to an interruption invoked by a Hardware (the Button in this example). The idea is that when we push the button the execution of the Main function will be interrupted to execute the service routine that will read the state of the LED and change it.

You might be wondering, why ISR? Why don’t we write a code that reads the state of the switch (button) and reacts to any change? The answer is simple, if you write such a code you have to call it regularly to read the state of the switch. However you will have to time when you press the switch so that you do it when the code is being executed. Otherwise if you press and release the button outside of this interval (when the code is not being executed) nothing will happens, the PI won’t detect that the button was pressed.

By using an interrupt is a signal we are telling the Pi to stop whatever it’s currently doing and do something else. So, if we connect the switch to a GPIO port and defined that port is an interrupt, whenever the Pi detects a change in state of the port (when the button is pressed), it would activate the interrupt routine, and our code would have to handle that interruption.

Note: This is a very simple explanation if you want to read more information Wikipedia and the references included in the article.

The Circuit

The circuit we are going to make is similar to the one on the previous post, we just add the pushbutton and change the GPIO used to connect the LED.

Note: if you want to review the basic for making a circuit read my previous post, there you will find a simple explanation of every component we use for the circuit, how do those components works, how to calculate the resistor value, and how to make the circuit with the breadboard.

As you can see from the Figure we are connecting one end of the LED (cathode) to the GPIO 17 (physical port #11) the other end (anode) to the resistor and the resistor is connected to the supply (3.3V, physical port #1). The pushbutton is connected to the GPIO 5 (physical port #29) and to ground (GND, physical port # 39).

For the value of the resistor we will use the same 330Ω (or any value higher than 165Ω).

R = V/I = (3.3V-1.7V)/0.02A = 80Ω
R = V/I = (5V-1.7V)/0.02A = 165Ω

Notice In the above calculations 1.7V represents the voltage drop of the LED and 0.02A is the max current of the LED. In my previous post there is a better explanation regarding these calculations.

Once you make the circuit it will look something like this.

The black cables represent ground (GND) and red cable are the Supply (3.3V), the orange and green cables are connected to the GPIOs 17 and 5 respectively.

To finish with the circuit, I think it is important to mention that there might be some false signals during the button press and release, this is because we are using a mechanical switch (pushbutton) therefore there is some jitter on the detection of the state change of the switch. These effect (false signals during the press and release of the button) known as Bouncing, can be “de-bounce” it in several different ways, such as a de-bouncer circuit (hardware) or if you prefer we can also de-bounce it with a de-bouncer program (software). We won’t be worrying about the switch bouncing but if you wish to read more about these pages give a very simple explanation: (page 1) (page 2).

The Program

Let us continue by writing the program to test our Button and LED circuit. First do not forget to create a folder to store your projects files on your Raspberry Pi.

Open your Visual Studio create a new C# Console Application and name it (in my case I named it PiButtonLed). With the project is created we need to add the WiringPi.dll file to our references. So, on the Solution Explorer right-click on the References node and select Add Reference…

The Reference Manager windows will open. In there, browse to WiringPi.dll file we created previously, selected and click Ok.

Confirm that WiringPi.dll was added to the References and do not forget to add a using statement for the WiringPi (using WiringPi).

Now let’s code. The program will have the following steps:

  1. Initialize the GPIO
  2. Tell the Pi we will send data out the GPIO
  3. Make sure LED is initially OFF
  4. Initialize the Interrupt Service Routine (ISR)
  5. Ask the user to press the button to turn the LED ON/OFF
  6. Or ask the user to press any key to exit.

The complete programs is here:

using System;
using WiringPi;

namespace PiButtonLED
    class Program
        //Place the LED on GPIO 17 (physical pin 11)
        const int redLed = 11;
        //Place the Button on GPIO 5 (physical pin 29)
        const int button = 29;

        static void Main(string[] args)
            // Tell the user that we are attempting to start the GPIO
            Console.WriteLine("Initializing GPIO Interface");

            // Any value less than 0 represents a failure 
            if (Init.WiringPiSetupPhys()  LED is OFF
            GPIO.digitalWrite(redLed, (int)GPIO.GPIOpinvalue.High);

            //Tell the user that the Interrupt Service Routine (ISR) is starting
            Console.WriteLine("Initializing ISR");

            // The interrupt will be called when the button is released -> (InterruptLevels.INT_EDGE_FALLING)
            // Initialize ISR
            if (GPIO.PiThreadInterrupts.wiringPiISR(button, (int)GPIO.PiThreadInterrupts.InterruptLevels.INT_EDGE_FALLING, buttonPressed) < 0)
                //Tell the user that ISR did not initialize
                throw new Exception("ISR Initialization Failed!");

            //Tell the user to press button to turn ON/OFF the LED OR to press any key to exit
            Console.WriteLine(".\n.\nPress the button to turn the LED ON/OFF");
            Console.WriteLine("Or press any key and then press the button to exit");
            // Wait for a key to be pressed
            // Turn LED OFF
            GPIO.digitalWrite(redLed, (int)GPIO.GPIOpinvalue.High);

        static void buttonPressed()
            //is the LED ON or OFF?
            if (GPIO.digitalRead(redLed) == (int)GPIO.GPIOpinvalue.Low)
                //Turn LED OFF
                GPIO.digitalWrite(redLed, (int)GPIO.GPIOpinvalue.High);
                //Turn LED ON
                GPIO.digitalWrite(redLed, (int)GPIO.GPIOpinvalue.Low);

Once you finish writing your code compile it using the Build option.

We are now ready to deploy our project. So let us connect to the Pi from our windows PC and transfer the PiButtonLed.exe and WiringPi.dll files that were created when we compiled our code. (I use PuTTY to connect to the Pi, and from the Windows command prompt use the command pscp source destination to transfer files). (Note I previously created the PiButtonLed directory for my project)

Then, from the PuTTy Terminal connected to the Pi, navigate to the folder to which you transferred the files (PiButtonLed in my case). Once there we can run our application with the following command: sudo mono PiButtonLed.exe.

You will see the message “Press the button to turn the LED ON/OFF” and in the next line the message “Or press any key and then press the button to exit”. Press the button…

The LED should turn ON (as it is set to be initially OFF), if you continue pressing the button you turn the LED ON/OFF accordingly. You will also experience false signals because of the Bouncing effect of the mechanical switch.

So, we did it! We could read and write using the Raspberry Pi. Therefore, for my next post I might try both denouncing scenarios Hardware and Software, or maybe just try a whole new project, let us see what it comes.

See you!…


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s