Raspberry Pi and GPIO in C

I will just hack Paul, N6HZ’s C program which already reads the KPOD since it already has a loop looking for KPOD “events”. In fact, it sort of does what this pseudocode does, except the code in italics:

try:
    loop:
        if rocker left position:
            read encoder
            move left stepper by encoder amount
        else
             read encoder
             move right stepper by encoder amount
except:
   politely shut down

The code that I need to add is GPIO code, and I found a wiki with examples here:

http://elinux.org/RPi_GPIO_Code_Samples#C.23

/*
   pulse.c
 
   gcc -o pulse pulse.c -lpigpio -lrt -lpthread
 
   sudo ./pulse
*/
 
#include <stdio.h>
 
#include <pigpio.h>
 
int main(int argc, char *argv[])
{
   double start;
 
   if (gpioInitialise() < 0)
   {
      fprintf(stderr, "pigpio initialisation failed\n");
      return 1;
   }
 
   /* Set GPIO modes */
   gpioSetMode(4, PI_OUTPUT);
   gpioSetMode(17, PI_OUTPUT);
   gpioSetMode(18, PI_OUTPUT);
   gpioSetMode(23, PI_INPUT);
   gpioSetMode(24, PI_OUTPUT);
 
   /* Start 1500 us servo pulses on GPIO4 */
   gpioServo(4, 1500);
 
   /* Start 75% dutycycle PWM on GPIO17 */
   gpioPWM(17, 192); /* 192/255 = 75% */
 
   start = time_time();
 
   while ((time_time() - start) < 60.0)
   {
      gpioWrite(18, 1); /* on */
 
      time_sleep(0.5);
 
      gpioWrite(18, 0); /* off */
 
      time_sleep(0.5);
 
      /* Mirror GPIO24 from GPIO23 */
      gpioWrite(24, gpioRead(23));
   }
 
   /* Stop DMA, release resources */
   gpioTerminate();
 
   return 0;
}

 

There are also some video examples out there:

https://www.youtube.com/watch?v=jY7KVruyGjs

One thing I learned is that I can get rid of using vi as my editor and use vim or nano:

It looks like this level of C code is actually much simpler than the C# code I wrote at Travana – which was a complex parser using the “Builder” pattern.

The only trick will be figuring out how to map whatever values are sent by the KPOD and translate these values into something the GPIO library can accept as a parameter. I already have the code hacked so it does this:

I think this will be big fun and that I am certainly up for the challenge!

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

%d bloggers like this: