I'm trying to communicate with MCP3008 ADC via SPI using "pigpio" library. Basically I'm trying to read an IR Sensor and I've managed to do it manually by sending the required signals but I can only read distances from 5 to 15 cm instead of 5 to 30 cm (I already tested in Arduino and It works fine), so I'm trying another approach. The only problem I have is that in "pigpio" we have the spiXfer() function to read and write from/to the ADC but I don't understand how the rxBuf and txBuf works, since they are char types. I would appreciate some help in how to read and write the bytes needed for this communication between the RPi and the ADC.


Using a char type to hold bytes is fairly common in C. char is one of the basic C types and holds one byte.

Here is some C code to read channel 0 of the MCP3008. The example should make clear how the functions are used.

#include <stdio.h>
#include <stdlib.h>

#include <pigpio.h>

   gcc -pthread -o mcp3008 mcp3008.c -lpigpio

int main(int argc, char *argv[])
   int i;
   int h;
   int v;
   int loops;
   int speed;
   double start, diff, sps;
   unsigned char buf[3];

   if (argc > 1) loops = atoi(argv[1]);
   else loops = 1000000;

   if (argc > 2) speed = atoi(argv[2]);
   else speed = 1000000;

   if (gpioInitialise() < 0) return 1;

   h = spiOpen(0, speed, 0);

   if (h < 0) return 2;

   start = time_time();

   for (i=0; i<loops; i++)
      buf[0] = 1;
      buf[1] = 128;
      buf[2] = 0;

      spiXfer(h, buf, buf, 3);

      v = ((buf[1]&3)<<8) | buf[2];

      printf("%d\n", v);

   diff = time_time() - start;

   fprintf(stderr, "sps=%.1f @ %d bps (%d/%.1f)\n",
      (double)loops / diff, speed, loops, diff);



   return 0;
  • Two more questions. 1) If I want to do any math with those numbers I need to convert them to int or float right? 2) If I want to use SPI1 (don't know if I should) where do I do it ? Thanks for all your help!!! Feb 12 '18 at 14:40
  • 2
    No, you can do math with char types. They are actually integral. Just beware the difference between signed and unsigned (which is the same as with other integral types). When working with bytes you usually want the latter.
    – goldilocks
    Feb 12 '18 at 14:44
  • I just read more about the char types. I had another mindset when thiking about that type. Feb 12 '18 at 14:49
  • @joan, I can't use spiXfer() when i declare the buf variable as unsigned char because spiXfer() expects char*. Is there anyway I can bypass this? Feb 13 '18 at 14:45
  • Yes, don't declare it as unsigned char. Just assign the variable to an unsigned char afterwards or cast it to unsigned. I.e. leave the function alone, just post process the data. Alternatively cast the unsigned char to char in the function call.
    – joan
    Feb 13 '18 at 16:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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