Communicate with Arduino over SPI
I want send data to/from Arduino Leonardo over SPI using wiringPi/pi4j on Raspberry, using custom GPIO as CS. Raspberry is supposed to be the master, and Arduino slave
First my setup:
Raspberry Pi 3B
Arduino Leonardo
Connection:
SCK – RPi pin 23 -> Arduino pin 13
MOSI – RPi pin 19 -> Arduino pin 11
MISO – RPi pin 21 -> Arduino pin 12
CS – RPi pin 27 (GPIO) -> Arduino pin 10
I’m using Java and Pi4j v1.4 library on Raspberry, made sure to activate SPI using sudo raspi-config
Now the code:
Raspberry
import com.pi4j.wiringpi.Spi;
import com.pi4j.wiringpi.Gpio;
///
int fd = Spi.wiringPiSPISetup(0. 9600);
if(fd <= -1) {
// never triggered, initializes correctly
System.out.println("SPI SETUP FAILED");
return;
}
Gpio.pinMode(0, Gpio.OUTPUT); // physical pin 27 equals GPIO 0 in WiringPi
byte someData[] = new byte[3];
someData[0] = 0x11;
someData[1] = 0x22;
someData[2] = 0x33;
Gpio.digitalWrite(0, false);
Spi.wiringPiSPIDataRW(0, someData, 3);
Gpio.digitalWrite(0, true);
And Arduino
#include
volatile int i = 0;
byte myArray[2];
void setup()
{
Serial.begin(9600);
pinMode(SS, INPUT_PULLUP);
pinMode(MOSI, OUTPUT);
pinMode(SCK, INPUT);
SPCR |= _BV(SPE);
SPI.attachInterrupt(); //allows SPI interrupt
}
void loop(void)
{
if (i == 2)
{
int x = (int)myArray[0]<<8|(int)myArray[1];
Serial.print("Received 16-bit data item from Master: ");
Serial.println(x, HEX);
i=0;
Serial.println("=============================================");
}
}
ISR (SPI_STC_vect) //Inerrrput routine function
{
myArray[i] = SPDR;
i++;
}
Raspberry Pi code is based on SPI Example in Pi4j, and Arduino code is borrowed from here
The result is that nothing is printed in Arduino serial monitor, so nothing arrives.
Am I missing something? I know that logical levels are different between Raspberry (3,3V) and Arduino (5V), but when tested with just digitalRead(10) (SS) Arduino catches setting GPIO from PI just fine. Can this be the issue? If not, what am I doing wrong?
Read more here: Source link
