-4

Hello and please do not delete right away. I'm having trouble finding good CODE examples for the I2C/SPI programming on the Raspberry Pi using C++. I've looked at wiringPi and other sources but they don't give much documentation with their source code as I would like. Has anyone found pleasant examples in either well documented source code or even video explanations? If you have could you please share a link?

Thank you!

  • The request of libraries, tutorials or similar are off-topic in SO – eyllanesc Sep 11 '17 at 03:42
  • Suggestion for where I should move it? perhaps StackExchange? – Brandon Williams Sep 11 '17 at 03:44
  • see this: https://raspberrypi.stackexchange.com/ – eyllanesc Sep 11 '17 at 03:45
  • 1
    @eyllanesc No. This question is off-topic there too. See the [Help Center there](https://raspberrypi.stackexchange.com/help/on-topic): "But please note that the following is off topic" "Asking for references to online material (use a search engine, and if that does not work, ask about the issue directly)" –  Sep 11 '17 at 04:00
  • do not know the rules of https://raspberrypi.stackexchange.com, I only recommended that you find out if you can post it there. – eyllanesc Sep 11 '17 at 04:28

1 Answers1

2

Doing I2C in C on Raspberry Pi is easy -- mostly you need ordinary low-level file operations -- open, read, write, etc.

First open the appropriate device:

int f = open ("/dev/i2c-1", O_RDWR);

Then use ioctl() to set the I2C device address:

ioctl (f, I2C_SLAVE, address);

Then just use ordinary read() and write() calls to send and receive data.

The hard part is understanding the data protocol of the device -- this may, or may not, be documented. For RPi, many vendors only provide Python programming examples, so we have to reverse-engineer the actual protocol from the Python code.

I've used this method for interfacing all manner of devices to the RPi -- displays, motors, sensors, etc. Honestly, reading and writing the I2C bus is very much the easy part of the job :)

Kevin Boone
  • 4,092
  • 1
  • 11
  • 15
  • But how do you do that in modern C++? Specifically, what are the files to include, and what namespace do those functions belong to? – Bob Aug 20 '20 at 00:23
  • read(), write(), ioctl() are in the global namespace, so you should be able to write "::read(...)", etc., in C++. You shouldn't need to include anything else. Having said that, there might be class libraries for C++ that wrap I2C operations. If there are, these might be easier to use than low-level function calls. – Kevin Boone Aug 21 '20 at 10:38
  • Of course you are right; my expectation was std::, but of course, I was wrong on that one... – Bob Aug 22 '20 at 14:26