1

I've been searching google and stackexchange for quite a while: I would like to access an ADC (MCP3201) via SPI, to do so, I have to use Python and would like to use WiringPi. Sadly it seems impossible to find any documentation on the wiringPi python bindings.

In C, the functions look as follows:

int wiringPiSPISetup (int channel, int speed); //returning filedescriptor int wiringPiSPIDataRW (int channel, unsigned char *data, int len);

They seem to exist (checked with ipython -> 'import wiringpi' -> 'wiringpi.' -> tab pressed twice) as python bindings.

Has anyone ever used the wiringPi SPI functions with python?

If so, please explain to me how to do it or point me into the right direction.

System is: Raspberry Pi 2 running raspbian jessie

Any help is appreciated,
Sebastian

P.S.: So far I tried the following code, executing it returns an error that it only accepts exactly 2 parameters.

import wiringpi

wiringpi.wiringPiSetupGpio()
SPIchan = 1
SPIspeed = 800000
wiringpi.wiringPiSPISetup (SPIchan, SPIspeed)

data = 0xAA
numberOfBytes = 2
wiringpi.wiringPiSPIDataRW(SPIchan, data, numberOfBytes)

print "Returned data: " + data

P.P.S: Found the wrapper for the C function: In Python, the wiringPiSPIDataRW() receives the channel and data to send as arguments, and returns the received data. However, using this function with 2 arguments just aborts the python script. Does anyone have any ideas how to get this function to work?

1

I had the honor to talk to the man himself, Mr. Gadgetoid.

Turns out that (in python) wiringPiSPIDataRW() accepts the 2 values channel (which SPI CE to use) and data. Data has to be a bytes() value (or in python2.7 a chr() or str() type).

So to sum up, the code to send and receive data looks as follows:

import wiringpi
SPIchannel = 1 #SPI Channel (CE1)
SPIspeed = 500000 #Clock Speed in Hz
wiringpi.wiringPiSetupGpio()
wiringpi.wiringPiSPISetup(SPIchannel, SPIspeed)

sendData = str(42) #will send TWO bytes, a byte 4 and a byte 2
recvData = wiringpi.wiringPiSPIDataRW(SPIchannel, sendData)
#recvData now holds a list [NumOfBytes, recvDataStr] e.g. [2, '\x9A\xCD']

#alternatively, to send a single byte:
sendData = chr(42) #will send a single byte containing 42
recvData = wiringpi.wiringPiSPIDataRW(SPIchannel, sendData)
#recvData is again a list e.g. [1, '\x9A']

Thats what works for me in Python 2.7, afaik you can use bytes() instead of str()/chr() in python 3 (not verified yet)

Thanks again to Philip,
Sebastian

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.