Skip to content

Instantly share code, notes, and snippets.

@tmeissner
Created December 9, 2012 19:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tmeissner/4246604 to your computer and use it in GitHub Desktop.
Save tmeissner/4246604 to your computer and use it in GitHub Desktop.
Generic function to send commands over the SPI interface of an AVR uC
// defines for all commands and the max length of spi messages
#define CHIPERASE "\xc7\x94\x80\x9a"
#define SPILENGTH 32
// array to receive data
unsigned char spi_rxdata[SPILENGTH];
// transfer a byte on spi
static unsigned char spi_transfer (unsigned char c) {
SPDR = c;
while (!(SPRS & (1<<SPIF))) {}
return SPDR;
}
// function to send commands & receive data over the spi if
static int spi_sendcmd (unsigned char *received, unsigned char *command, uint8_t length) {
if (length>SPILENGTH) {
return -1;
}
// activate slave select
PORTB &= ~(1<<PB2);
for (int index=0; index<length; index++) {
received[index] = spi_transfer(command[index]);
}
// deactivate slave select
PORTB |= (1<<PB2);
return index;
}
// call the function
spi_rxdata_length = spi_sendcmd(spi_rxdata, CHIPERASE, sizeof(CHIPERASE)-1);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment