How to get SpiDev working on a Raspberry PI

651 Views Asked by At

I'm new to both Python and Raspberry Pi, so I expected a learning curve, but this is one that I think I'll need help with. The Raspberry Pi will need to communicate with external hardware through SPI. I've enabled SPI on the Raspberry Pi and installed all the requisite libraries.

Here is the code.

#test program for spi

import spidev
import RPi.GPIO as GPIO
from time import sleep

bus = 0                     #always 0, apparently
device = 0                  #we will use our own CS pin

mode = 3                    #see SPI modes
maxSpeed = 100000           #maximum clock speed in Hz
noCs = True                 #hardware CS
lsbFirst = False            #MSB first is default

##############################################################
CS_PIN = 24                 #CS pin number
WRITE_DATA = [0x4D, 0x4D, 0x4D]
##############################################################


if __name__ == '__main__':
    #config GPIO
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(CS_PIN, GPIO.OUT)
    GPIO.setwarnings(False)
    
    GPIO.output(CS_PIN, True)
    
    #config SPI
    spi = spidev.SpiDev()
    spi.open(bus, device)
    spi.mode = mode
    spi.no_cs = noCs
    spi.lsbfirst = lsbFirst
    spi.max_speed_hz = maxSpeed

    #run SPI
    GPIO.output(CS_PIN, False)
    spi.xfer(WRITE_DATA)
    GPIO.output(CS_PIN, True)
    sleep(0.1)
    #print data
    '''
    listLen = len(readbytes)
    print("Lenght: ", listLen)

    i = 0
    while i < listLen:
        print("Byte ", i, ": ", readbytes[i])
        i += 1
    '''
    GPIO.cleanup()

The program I wrote didn't work, so I wrote a simple test program (the code above). I was able to look at the SPI signals with an oscilloscope. I didn't see anything on MOSI, so I checked SCK, and it too did not appear to be oscillating.

To observe these signals, I set a falling edge trigger at about 2V. Both of the signals are high. I am able to see the CS signal go low and then high, but it's controlled with GPIO.

The SpiDev code is supposed to be easy to use, but I'm at my wits end with this one.

0

There are 0 best solutions below