Arduino Nano Every Example: "Configure Nano Every as SPI - SLAVE"
I was searching for a solution for Arduino Nano Every to set it up as SPI Slave, but I was not able to find a working C-Code (like copy paste) for this deadicated MCU.
Therefore, I've tried it out with two Arduino Nano Every Boards by myself and I could figure out a ready to use solution:
Connection overview:
Master <-> Slave
SCK (D13) <-> SCK (D13)
MISO / CIPO (D12) <-> MISO / CIPO (D12)
MOSI / COPI (D11) <-> MOSI / COPI (D11)
CS / SS (D8) <-> CS / SS (D8)
GND <-> GND
Both Arduino Boards are connected to the PC (with 2 separate USB cables).
Master Code:
#include <SPI.h>
void setup (void) {
Serial.begin(9600); //set baud rate
pinMode(SS, OUTPUT);
digitalWrite(SS, HIGH); // disable Slave Select
SPI.begin ();
SPI.setClockDivider(SPI_CLOCK_DIV32);//divide the clock
}
void loop (void) {
char c;
digitalWrite(SS, LOW); // enable Slave Select
// send test string
for (const char * p = "This is a TEST!\n" ; c = *p; p++)
{
SPI.transfer (c);
Serial.print(c);
}
digitalWrite(SS, HIGH); // disable Slave Select
delay(2000);
}
Slave Code:
#include <avr/io.h>
#include <avr/interrupt.h>
void setup() {
// ... Serial initialization and other setup ...
Serial.begin(9600); //set baud rate
// NOTE: https://ww1.microchip.com/downloads/aemDocuments/documents/MCU08/ApplicationNotes/ApplicationNotes/TB3215-Getting-Started-with-SPI-DS90003215.pdf
//PORTMUX.TWISPIROUTEA &= ~PORTMUX_SPI00_bm; // cleared by default -> nothing to do
PORTMUX.TWISPIROUTEA |= PORTMUX_SPI01_bm; // set Portmux bit SPI01 for alternative mapping of SPI pins
// SPI in slave mode
SPI0.CTRLA = SPI_DORD_bm | SPI_ENABLE_bm & (~SPI_MASTER_bm);
// Set pin modes
PORTE.DIR &= ~PIN0_bm; // MOSI
PORTE.DIR |= PIN1_bm; // MISO
PORTE.DIR &= ~PIN2_bm; // SCK
PORTE.DIR &= ~PIN3_bm; // CS / SS
// Interrupt setup
sei(); // Enable global interrupts
SPI0.INTCTRL = SPI_IE_bm; // SPI Interrupt enable
SPI0.INTFLAGS |= SPI_IF_bm; // clear interruptflag - not cleared automatically
}
// SPI interrupt routine
ISR(SPI0_INT_vect) {
Serial.print("ISR - Triggered!\n");
SPI0.INTFLAGS |= SPI_IF_bm; // clear interruptflag - not cleared automatically
}
void loop() {
Serial.print("And a new loop!\n");
delay(5000);
}
I'll format this post maybe a little bit better in future, but I think that will help some guys, who are searching for exactly such a "template".
BR