vsergeev / python-periphery

A pure Python 2/3 library for peripheral I/O (GPIO, LED, PWM, SPI, I2C, MMIO, Serial) in Linux.
MIT License
519 stars 139 forks source link

SPI transaction speed not meeting the maximum speed #56

Open sjpark608 opened 1 year ago

sjpark608 commented 1 year ago

Hi,

I am using SPI module in the library to handle SPI transactions from Raspberry PI CM4 to an onboard SPI device. The maximum speed is set to 5MHz on my script, and when I performed spi.transfer() of 7 bytes, the measurement time was well above the expected time.

I am trying to sample data at 38400SPS which is about 1 / 21us, but due to the delay of SPI transaction, I cannot actually achieve the sampling rate. I was wondering if you have any idea on how to increase the transaction speed of the SPI.

The following is my piece of code

spi = SPI("/dev/spidev6.1", mode = 1, max_speed = 5000000)
def read_data_bytes(spi, adc_type):
    if adc_type == 1:
        values = [RDATA1_OP] + [0xFF]*6
    else:
        values = [RDATA2_OP] + [0xFF]*6
    _logger.info(f'Sending Command = {values}')
    t1_start = perf_counter()
    values = spi.transfer(values)
    t1_stop= perf_counter()
    _logger.info(f'Reading ADC data= {values}, Tx time {t1_stop - t1_start}')
    return values
INFO:__main__:Reading ADC data= b'``\xf35{$b', Tx time 0.00021887299953959882
INFO:__main__:Data in decs = (96, 96, 243, 53, 123, 36, 98)

When scoped the MISO and Clock signal, I found out that the clock signal is not actually 5MHz, it's around 2MHz. And the CS is asserted much longer than it needs.

The following is captured image clk_and_MISO zoomed_in_clk clk CS

sjpark608 commented 1 year ago

The clock signal being slower than the maximum clock speed set in SPI module was due to the RPI core clock divisor. I've resolved the issue by configuring dt-overlay.

I'm still having issue with the CS line being asserted and de-asserted long before and after the transmission. Is there a way to assert the line faster?