SPI communication between RP2040 and RPi CM4

67 Views Asked by At

This is my pin mapping between the RP2040 and RPi CM4 for SPI communication:

RP2040 Raspberry Pi (SPI0) GPIO 3 (MISO) GPIO 9 (MISO) GPIO 0 (MOSI) GPIO 10 (MOSI) GPIO 2 (SCLK) GPIO 11 (SCLK) GPIO 1 (CS) GPIO 8 (CE0)

This is the RP2040 code:

#define SPI_PORT spi0
#define SPI_BAUD_RATE 1000000
#define PIN_MISO 3
#define PIN_MOSI 0
#define PIN_SCLK 2
#define PIN_CS 1

static uint8_t rx_buffer[256];
static uint8_t event_buffer[256];
static uint8_t event_buffer_index = 0;

static void parse_received_data(uint8_t *data, uint length);

void rpi_communicate()
{
    uint len = spi_read_blocking(SPI_PORT, 0, rx_buffer, sizeof(rx_buffer));
    if (len > 0)
    {
        printf("SPI Received Data: ");
        for (uint i = 0; i < len; i++)
        {
            printf("%02x ", rx_buffer[i]);
        }
        printf("\n");

        parse_received_data(rx_buffer, len);

        // Send back the response data
        spi_write_blocking(SPI_PORT, rx_buffer, len);
    }
}

void rpi_init()
{
    spi_init(SPI_PORT, SPI_BAUD_RATE);
    spi_set_slave(SPI_PORT, true);
    spi_set_format(SPI_PORT, 8, SPI_CPOL_0, SPI_CPHA_0, SPI_MSB_FIRST);

    gpio_set_function(PIN_MISO, GPIO_FUNC_SPI);
    gpio_set_function(PIN_MOSI, GPIO_FUNC_SPI);
    gpio_set_function(PIN_SCLK, GPIO_FUNC_SPI);
    gpio_set_function(PIN_CS, GPIO_FUNC_SPI);

    // Set up SPI interrupt
    irq_set_exclusive_handler(SPI0_IRQ, rpi_communicate);
    irq_set_enabled(SPI0_IRQ, true);
    spi_get_hw(SPI_PORT)->imsc = 1 << 2; // Enable RX FIFO interrupt (RXIM)

    printf("\nSPI Initialized - 2 ...");
}

The RPi CM4 Code:

import spidev
import threading
import time


# Initialize SPI device
spi = spidev.SpiDev()
spi.open(0, 0)  # Use SPI bus 0, device 0
spi.mode = 0
spi.max_speed_hz = 1000000

def send_command(command, data=None):
    if data:
        spi.xfer2([command] + data)
    else:
        spi.xfer2([command])

I have checked that the connections are proper, and I am able to toggle the pins from both sides as IO pins.

The RPi is a master and the RP2040 is a slave. When I try to send data in a loop to the rp2040, I can see the CE pin showing a square wave, but all the other pins seem to be quiet, and the communication is not working.

Any help is appreciated. Thanks.

0

There are 0 best solutions below