Monday, July 8, 2013

GPIO using the Raspberry Pi


After getting my OLED and GPS working, I wanted to mess around with the GPIO pins so I bit off something simple. Here is what my setup looks like.
  • Raspberry Pi
  • Raspberry Pi T Cobbler
  • Raspberry Pi Ribbon Cable
  • Breadboard
  • Two 1 KiloOhms resistors
  • Two 10 KiloOhms resistors - pull up resistors
  • 2 momentary pushbuttons
  • Jumper wires
In this setup, pushing the button will drive the signal low. To keep things simple and just illustrate the point, pushing the button(s) will just print out a message to stdout. In doing some research, I came across Gordon's wiringPi library. I incorporated this into my code so I didn't have to reinvent the wheel! It is pretty simple to use for my C++ application. I started out the simple way and had a loop to check the pin status and act upon it if it has changed. However, that doesn't fit my end goal so I got a bit fancier with the implementation, but the good news is that it is supported by wiringPi. The fancier implementation is to use interrupts and to have a function pointer called when the interrupt is detected. Below is the code to drive this circuit. Currently, the circuit does bounce so debouncing code will need to be added to normalize this, but hopefully this illustrates the point.
#include <iostream>
#include <wiringpi.h>

// These are wiringPi pin numbers from http://wiringpi.com/pins
#define BUTTON_1     7  // pin 7 on pi
#define BUTTON_2     3  // pin 15 on pi

using namespace std;

void interruptHandler ()
{
   cout << "in interruptHandler()" << endl;
}

void interruptHandler2 ()
{
   cout << "in interruptHandler2()" << endl;
}

int main ()
{
   if (wiringPiSetup() < 0)
   {
      cout << "uniable to initialize wiringPi library!" << endl;
      return 1;
   }

   if (wiringPiISR (BUTTON_1, INT_EDGE_FALLING, &interruptHandler) < 0)
   {
      cout << "Unable to register interrupt handler for BUTTON_1!" << endl;
      return 1 ;
   }

   if (wiringPiISR (BUTTON_2, INT_EDGE_FALLING, &interruptHandler2) < 0)
   {
      cout << "Unable to register interrupt handler for BUTTON_2!" << endl;
      return 1 ;
   }

   // wait for interrupt, but don't consume 100% of cpu
   while (1)
      delay (100);

   return 0;
}

No comments :

Post a Comment