VIM3 I2C Python Example

https://docs.khadas.com/vim3/HowToUseWiringPi-Python.html lists the functions available for wiringpi in python and gives a simple example of the pins usage but doesnt explain how to make it work, or how to use I2C. So I just wanted to capture how to get the wiringpi-python working on a VIM3. Hopefully useful to others (and will mean I can find it again when I forget :slight_smile:)

  1. first off we need to install wiringpi-python, so go here and follow the instructions https://github.com/khadas/WiringPi-Python#manual-build . Note that to get this working with python3 the prerequsites required are as follows - sudo apt install python3-dev python3-setuptools swig

  2. Then we can test the setup with a bit of test code. Find a device to test against by using the command “i2cdetect -y 3”. That will return all the I2C devices connected to the VIM3 bus (GPIO pins 22 and 23) - in my case my device is at address 0x10 (note hex notation). Once we have a device then put the address into the following code and run it using python3:

      import wiringpi
    
      result = wiringpi.wiringPiSetup();
      print("wiringpi setup result = ",result);
    
      #fd = wiringpi.wiringPiI2CSetupInterface("/dev/i2c-4",0x10);
      fd = wiringpi.wiringPiI2CSetup(0x10);
      print("I2C setup result = ", result);
    
      result = wiringpi.wiringPiI2CReadReg8(fd,0x22);
      print("I2C read result = ", result);
    

If all is working then you should get an output that looks something like - the first two should be 0, if they are negative then something has gone wrong and the final one is the value read back from the device at I2c bus address 0x10 and register addres 0x22 in that device:

     wiringpi setup result =  0
     I2C setup result =  0
     I2C read result =  246

Note that if you want to use the I2C bus on pins 25 and 26 of the VIM3 GPIO header then you need to use the commented out line above instead of the one below it to setup wiringpiI2C against /dev/i2c-4 instead of the default /dev/i2c-3 device.

Hope thats of use to people in the future

4 Likes