0

How do I need to modify the C example from http://abyz.me.uk/rpi/pigpio/examples.html for continious monitoring of Wiegand readers?

I need to run it as background process.

For now I have a code:

#include <stdio.h>
#include <pigpio.h>
#include "wiegand.h"


void callback1(int bits, uint32_t value)
{

    FILE *saved = stdout;
    stdout = fopen("log_readers.txt", "a");
    printf("Reader_1: bits=%d value=%u\n", bits, value);
    fclose(stdout);
    stdout = saved;
}

void callback2(int bits, uint32_t value)
{
   FILE *saved = stdout;
   stdout = fopen("log_readers.txt", "a");   
   printf("Reader_2: bits=%d value=%u\n", bits, value);
   fclose(stdout);
   stdout = saved;
}

int main(int argc, char *argv[])
{
   Pi_Wieg_t * w1;
   Pi_Wieg_t * w2;
   if (gpioInitialise() < 0) return 1;
   w1 = Pi_Wieg(14, 15, callback1, 5);
   w2 = Pi_Wieg(23, 24, callback2, 5);
   sleep(300);
   Pi_Wieg_cancel(w1);
   Pi_Wieg_cancel(w2);
   gpioTerminate();
}

After 5 minutes of execution it's terminated, I suppose cause of sleep(300). If I wrap it by infinite loop like this:

int main(int argc, char *argv[])
    {
    while(0) {
      Pi_Wieg_t * w1;
      ...
    }
}

it's terminated immediately after running.

2 Answers 2

2

The simplest way would probably be

int main(int argc, char *argv[])
{
   int done = 0;

   Pi_Wieg_t * w1;
   Pi_Wieg_t * w2;
   if (gpioInitialise() < 0) return 1;
   w1 = Pi_Wieg(14, 15, callback1, 5);
   w2 = Pi_Wieg(23, 24, callback2, 5);
   while (!done)
   {
      sleep(1);

      /* add code here to detect the exit condition (if any)
         and set done = 1
      */
   }
   Pi_Wieg_cancel(w1);
   Pi_Wieg_cancel(w2);
   gpioTerminate();
}
2

Your infinite loop condition is wrong - while (0) is the same as while false, which means the loop never gets run. Change this to while (1) and you get an infinite loop.

Regarding the first code - since the main loop only has a sleep(300) in it, it will terminate as soon as the sleep is over, since you have your Wieg_cancel and gpioTerminate calls straight after this.

You might want to study up a bit on how to write programs in C, as the above issues are very trivial.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.