Quantcast
Channel: Raspberry Pi Forums
Viewing all articles
Browse latest Browse all 1247

Python • SPI connect of Raspberry PI 4b and Zero 2W with pigpio

$
0
0
Hello,
I am trying to connect 2 raspberries by SPI and establish the connection. I chosen pigpio since as far as I understand this is the only lib which could help with SPI slave mode as well. So, I connected Zero 2W and 4B with GPIO 8, 9, 10, 11 and GND. MISO and MOSI connected vise versa(GPIO 9 to GPIO 10 and GPIO 10 to GPIO 9).
Also I started with couple simple programs for master:

Code:

import pigpioimport time# Initialize pigpiopi = pigpio.pi()if not pi.connected:    exit()# Open SPI master with device (0) and speed (400000 bps)handle = pi.spi_open(0, 4000000, 0)if handle < 0:    print("Failed to open SPI master")    exit()# Prepare some data to senddata = "Hello, SPI slave!"data = [ord(c) for c in data]  # Convert string to list of ASCII values# Send datacount = pi.spi_write(handle, data)if count < 0:    print("Failed to send data")else:    print("Sent data: ", data)# Read data(count, rx_data) = pi.spi_read(handle, len(data))if count > 0:    print("Received data: ", ''.join(chr(i) for i in rx_data))# Close SPI masterpi.spi_close(handle)pi.stop()
And for slave:

Code:

import pigpioimport timeCONTROL_WORD = (1 << 0) | (1 << 1) print(f'CONTROL_WORD = {CONTROL_WORD}')# Initialize pigpiopi = pigpio.pi()if not pi.connected:    exit()# Prepare some data to senddata = "Hello, SPI master!"data = [ord(c) for c in data]  # Convert string to list of ASCII valuestry:    # Main loop    while True:        # Check if there is a request from the master        status, count, rx_data = pi.bsc_xfer(CONTROL_WORD, [])        if count > 0:            print(f'Count {count}')            print("Received request from master: ", ''.join(chr(i) for i in rx_data))            # Send data in response to the request            status, count, tx_data = pi.bsc_xfer(CONTROL_WORD, data)            if status >= 0:                print("Sent data: ", data)        # Sleep for a bit        time.sleep(0.01)except KeyboardInterrupt:    print("\nTidying up")    pi.bsc_xfer(0, [])    pi.stop()# Close BSCpi.bsc_xfer(0, [])pi.stop()
As a result I got on the slave:
Count 16
Received request from master: ello, SPI slave!
Sent data: [72, 101, 108, 108, 111, 44, 32, 83, 80, 73, 32, 109, 97, 115, 116, 101, 114, 33]
But I do not see any message in response from the slave. I used the script monitor.py for GPIO monitor on both sides.
Also it works just in one side, when slave code is running on the pi 4B and Zero 2W as a master. Vise versa with the same code I got nothing.

I have also tried with single spi_xfer() on the master side, but result is the same. Please advise what could be a problem and how to get the data in response?

Statistics: Posted by archangel_87 — Thu Apr 11, 2024 8:50 pm



Viewing all articles
Browse latest Browse all 1247

Trending Articles