Ben
Ben

Reputation: 9

How to send data via SPI between Raspberry Pi and Arduino

I hope you can help.

I am currently using SPI to communicate between a Raspberry Pi (master) and Arduino (slave).

Currently, I have two codes, one for the master and the other the slave.

However, I am finding it difficult to transfer data across the two devices.

The Raspberry Pi code - master

import wiringpi
import iostream
import spidev
import time
import sys

spi = spidev.SpiDev()
SPI_CHANNEL = 0
SPI_CLOCK_SPEED = 1000000

def main():
    wiringpi.wiringPiSetup()
    fd = wiringpi.wiringPiSPISetup(SPI_CHANNEL, SPI_CLOCK_SPEED)

    if fd == -1:
        print("Failed to init SPI communication.")

    else:
        print("SPI communication successfully setup.")

        buff = [23, 0]
        wiringpi.wiringPiSPIDataRW(SPI_CHANNEL, buff)
        print("Data returned: ", buff[1])
        main()
        return 0

if __name__ == "__main__":
    main()

The Arduino code - slave

#include <SPI.h>
void setup() {
  // have to send on master in, *slave out*
  pinMode(MISO, OUTPUT);
  // turn on SPI in slave mode
  SPCR |= _BV(SPE);
  // turn on interrupts
  SPI.attachInterrupt();
}
// SPI interrupt routine
ISR (SPI_STC_vect)
{
  byte c = SPDR;
  SPDR = c+10;
}  // end of interrupt service routine (ISR) for SPI
void loop () { }

What happens when run? ...

Firstly I verify then upload the Arduino code, then run the raspberry pi script.

Within the Raspberry Pi terminal it prints: "SPI communication successfully setup".

From here two things can happen. Either the code just hangs, and does nothing or an error appears. The error states: Backend terminated or disconnected. Use 'Stop/Restart' to restart.

What should happen when run?...

The code should send the number 23 from the Raspberry Pi. The Arduino should receive 23 and +10. This new number (33) should be sent to the Raspberry Pi and printed within the Raspberry Pi terminal.

Other notes

Raspberry Pi

Arduino

What do I need help with? If possible...

Any help or advice would be great!

**EDIT

How are they connected?

I have the following connections Raspberry Pi on the left to the Arduino on the right.

What happens on the Arduino side?

Currently nothing happens in the arduino terminal. I presume this is because the code gets stuck at buf = [23, 0] on the raspberry pi code. Meaning nothing has been sent to the arduino.

Notes

Both devices have sufficient power.

Upvotes: 0

Views: 541

Answers (0)

Related Questions