Building an SPI Command with Arduino Due
Posted: Mon Aug 19, 2013 8:06 am
I need to construct a 24bit command which will be sent out 8bits at a time over the Arduino Due's SPI interface to a MAX5318 (a DAC with 18bit resolution). The first 4 bits are a command, and the next 18bits are the value to output, and the last 2 bits ignored. And since I have no experience at bit twiddling, I wanted to see if you guys knew a better, more efficient way than my proposal, which is as follows:
I have a struct of 3 bytes (a byte is a datatype in Arduino language), and several functions that take a int (a 32bit 2's complement in the Arduino Due). Currently my code looks like this:
My question is: there's got to be a better, more efficient way of doing this, right?
I have a struct of 3 bytes (a byte is a datatype in Arduino language), and several functions that take a int (a 32bit 2's complement in the Arduino Due). Currently my code looks like this:
Code: Select all
dacSPIframe dac_writeDIN(int number){
dacSPIframe command;
bitWrite(command.first,7,0);
bitWrite(command.first,6,0);
bitWrite(command.first,5,0);
bitWrite(command.first,4,1);
bitWrite(command.first,3,bitRead(number,31)); //since this is two's complement, gotta copy the sign over
bitWrite(command.first,2,bitRead(number,17)); //crap, this means I only get 17bit resolution?
bitWrite(command.first,1,bitRead(number,16));
bitWrite(command.first,0,bitRead(number,15));
... and maybe two for loops here to save myself from writing extra lines, finishing off with...
bitWrite(command.third,1,0);
bitWrite(command.third,0,0);
return command;
}
My question is: there's got to be a better, more efficient way of doing this, right?