hi
Trying to adapt this code by Nick Gammon from hereGammon-SPI
// Written by Nick Gammon
// April 2011
// what to do with incoming data
byte command = 0;
// start of transaction, no command yet
void ss_falling ()
{
command = 0;
} // end of interrupt service routine (ISR) ss_falling
void setup (void)
{
// have to send on master in, *slave out*
pinMode(MISO, OUTPUT);
// turn on SPI in slave mode
SPCR |= _BV(SPE);
// turn on interrupts
SPCR |= _BV(SPIE);
// interrupt for SS falling edge
attachInterrupt (0, ss_falling, FALLING);
} // end of setup
// SPI interrupt routine
ISR (SPI_STC_vect)
{
byte c = SPDR;
switch (command)
{
// no command? then this is the command
case 0:
command = c;
SPDR = 0;
break;
// add to incoming byte, return result
case 'a':
SPDR = c + 15; // add 15
break;
// subtract from incoming byte, return result
case 's':
SPDR = c - 8; // subtract 8
break;
} // end of switch
} // end of interrupt service routine (ISR) SPI_STC_vect
void loop (void)
{
// all done with interrupts
} // end of loop
I tried implementing the code on a tiny84. I had to change the
SPCR to USICR
SPDR to USIDR
ISR (SPI_STC_vect) to ISR (USI_OVF_vect).
I also set the mode like this, but as far as I can tell looking at the tiny84 datasheet it is equivalent.
USICR = (1 << USIWM0) // SPI mode
| (1 << USIOIE) // Enable interrupt
| (1 << USICS1); // Clock is external
It compiles and uploads fine, I just can’t get a return value.
here’s the code
// Written by Nick Gammon
// April 2011
#include "pins_arduino.h"
// what to do with incoming data
byte command = 0;
void setup (void)
{
pinMode(10, OUTPUT);
pinMode(9, OUTPUT);
pinMode(8, OUTPUT);
#define ss PB0
USICR = (1 << USIWM0) // SPI mode
| (1 << USIOIE) // Enable interrupt
| (1 << USICS1); // Clock is external
} // end of setup
// SPI interrupt routine
ISR (USI_OVF_vect)
{
byte c = USIDR;
switch (command)
{
// no command? then this is the command
case 0:
command = c;
USIDR = 0;
digitalWrite(10, HIGH);
digitalWrite(9, LOW);
digitalWrite(8, LOW);
break;
// add to incoming byte, return result
case 'a':
USIDR = c + 15; // add 15
digitalWrite(10, LOW);
digitalWrite(9, HIGH);
digitalWrite(8, LOW);
break;
// subtract from incoming byte, return result
case 's':
USIDR = c - 8; // subtract 8
digitalWrite(10, LOW);
digitalWrite(9, LOW);
digitalWrite(8, HIGH);
break;
} // end of switch
} // end of interrupt service routine (ISR) SPI_STC_vect
void loop (void)
{
// if SPI not active, clear current command
if (digitalRead (ss) == HIGH)
command = 0;
} // end of loop
the digitalWrite’s are for diagnostics. It looks like the switch case is working and I am receiving data just fine, I just can’t send it back to the master…
I’ve been struggling for weeks with this. I’ve learned a ton, I just cant get it to work >_<
thanks for any help you can offer.