Skip to content

Instantly share code, notes, and snippets.

@chrismeyersfsu
Created August 10, 2012 20:53
Show Gist options
  • Star 39 You must be signed in to star a gist
  • Fork 13 You must be signed in to fork a gist
  • Save chrismeyersfsu/3317769 to your computer and use it in GitHub Desktop.
Save chrismeyersfsu/3317769 to your computer and use it in GitHub Desktop.
Arduino SPI Slave
// Written by Nick Gammon
// February 2011
/**
* Send arbitrary number of bits at whatever clock rate (tested at 500 KHZ and 500 HZ).
* This script will capture the SPI bytes, when a '\n' is recieved it will then output
* the captured byte stream via the serial.
*/
#include <SPI.h>
char buf [100];
volatile byte pos;
volatile boolean process_it;
void setup (void)
{
Serial.begin (115200); // debugging
// have to send on master in, *slave out*
pinMode(MISO, OUTPUT);
// turn on SPI in slave mode
SPCR |= _BV(SPE);
// get ready for an interrupt
pos = 0; // buffer empty
process_it = false;
// now turn on interrupts
SPI.attachInterrupt();
} // end of setup
// SPI interrupt routine
ISR (SPI_STC_vect)
{
byte c = SPDR; // grab byte from SPI Data Register
// add to buffer if room
if (pos < sizeof buf)
{
buf [pos++] = c;
// example: newline means time to process buffer
if (c == '\n')
process_it = true;
} // end of room available
} // end of interrupt routine SPI_STC_vect
// main loop - wait for flag set in interrupt routine
void loop (void)
{
if (process_it)
{
buf [pos] = 0;
Serial.println (buf);
pos = 0;
process_it = false;
} // end of flag set
} // end of loop
@Jonathan-creator123
Copy link

Jonathan-creator123 commented Jul 15, 2022

MY result last verify in ARDUINO IDE, with Error attention is :
error: expected initializer before 'volatile' volatile byte pos;

1 #include <SPI.h>
2 char buf [100]
3 volatile byte pos;
4 volatile boolean process_it;

at Upper Program , What is same this my program too with that four line ?

@gormster
Copy link

gormster commented Aug 8, 2022

@Jonathan-creator123 you're missing a semicolon after char buf [100]

@robertocordon
Copy link

This is half of what I'm looking for, thanks so much!
Do you know how to (as a slave) send data to master as well?

@gormster
Copy link

Pretty sure you just write to SPDR.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment