Example Code for SPI Slave

Hello,

I seem to not be able to find example code for spi slave (with spidev) in any language for jetson nano.
I saw this post but there was no source code provided as well.
I have seen spidev_test, but couldn’t find the slave portion of it.
Is there some example code available?

1 Like

I recently got spi working with nano. But I’m not sure if it’s possible to configure nano as slave. I have some working code with nano as master, do you need example read and write functions? I’ve added my read and write example just in case. Let me know if you have any questions.

I may be missing some library in this code but it’s mostly there.

#include <linux/spi/spidev.h>

SPI_SPEED = 1000000;

int spi_send_msg(int spi_dev_fd, char addr, char * data, int len)
{
	char data_buffer[len + 1];
	char recv_buffer;
	struct spi_ioc_transfer xfer;	

	memset(&xfer, 0, sizeof(xfer));
	memset(&recv_buffer, 0, sizeof(recv_buffer));
	
	data_buffer[0] = addr;
	//printf("BUFF: %x\n", data_buffer[0]);
	for(int i = 1; i < len + 1; ++i)
	{
		data_buffer[i] = data[i-1];
		//printf("BUFF: %x\n", data_buffer[i]);
	}
	xfer.tx_buf = (unsigned long) data_buffer;
	xfer.rx_buf = (unsigned long) &recv_buffer;
	xfer.len = len + 2;
	xfer.bits_per_word = 8;
	xfer.speed_hz = SPI_SPEED;
	xfer.cs_change = 0;
	xfer.rx_nbits = 8;	// EXPERIMENT WITH THIS
	xfer.tx_nbits = (8 * len) + 8;
	
	int res = ioctl(spi_dev_fd, SPI_IOC_MESSAGE(1), xfer);

	return 0;

}

int spi_read_msg(int spi_dev_fd, char addr, char * copy_to, int len)
{
	char data_buffer;
	char recv_buffer[len];
	struct spi_ioc_transfer xfer;	

	memset(&xfer, 0, sizeof(xfer));
	memset(&recv_buffer, 0, sizeof(recv_buffer));

	data_buffer = addr;
	xfer.tx_buf = (unsigned long) &data_buffer;
	xfer.rx_buf = (unsigned long) recv_buffer;
	xfer.len = len + 1;
	xfer.bits_per_word = 8;
	xfer.speed_hz = SPI_SPEED;
	xfer.cs_change = 0;
	xfer.rx_nbits = len * 8;	// EXPERIMENT WITH THIS
	xfer.tx_nbits = 8;
	
	int res = ioctl(spi_dev_fd, SPI_IOC_MESSAGE(1), xfer);
	
	if(recv_buffer[0])
	{
		strcpy(copy_to, recv_buffer);
	}
	return 0;

}
1 Like

Hello @cap,
Thanks for the answer, I already configured the nano as slave, but I don’t know how to use it in code. Because as slave it needs to work with the CS and react to incoming messages, so I was expecting there to be example code.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.