diff --git a/main.cpp b/main.cpp index ce201d0..2f26725 100644 --- a/main.cpp +++ b/main.cpp @@ -11,9 +11,24 @@ //from the core and we need to include it explicitly #include -//Define which port to use for the SPI Chip Select +// Define which port to use for the SPI Chip Select by using the register +// definitions. The data direction register is assigned as well. +// The ports can be looked up on the official Arduino pinout schematics. +#ifdef ARDUINO_AVR_MEGA2560 +// Defines for the Arduino Mega +#define CS_PORT PORTK +#define CS_DDR DDRK +#elif defined(ARDUINO_AVR_UNO) +#define CS_PORT PORTD +#define CS_DDR DDRD +#elif defined(__SAM3X8E__) +// Define for the Arduino Due #define CS_PORT PORTC #define CS_DDR DDRC +#else +#define CS_PORT PORTC +#define CS_DDR DDRC +#endif static const uint8_t COMMAND_TRANSFER_SPI = 1; @@ -45,9 +60,13 @@ void sendData(uint8_t *data, size_t len) { void transferSPI(uint8_t address, uint8_t *data, size_t datalen) { SPI.beginTransaction(SPISettings(14000000, MSBFIRST, SPI_MODE3)); + // The specified address is the bit where the last bit is port 0 + // and the first bit is port 7. It is inverted because the SPI protocol + // requires the slave select to be driven low. CS_PORT = ~address; SPI.transfer(data, datalen); delay(100); + // Pull the slave select high again. CS_PORT = 0xff; SPI.endTransaction(); @@ -157,7 +176,10 @@ void serialEvent() { } void setup() { + // Set data direction of selected port to output. CS_DDR = 0xff; + // Drive all the slave selects high as required for the SPI protocol + // if no transfer is going on. CS_PORT = 0xff; Serial.begin(BAUD_RATE); Serial.println("Setting up Arduino IO interface board.");