I am attempting to send SPI data through an optocoupler level shifter. (Basically takes the 3.3v signal to a 5v signal)
In this process, the level shifter flips all the bits (inverted logic) instead of using another inverter to realign the signal, I decided it would be easier to simply send inverted bits out of the SPI port.
To do this, I set the mode on the chip select to active high and changed the clock polarity. Now I attempting to bit flip the data I am sending out.
unsigned short* tx;
unsigned short* rx;
while(!feof(data_file)){
fread(buffer, 2, 80, data_file);
tx = buffer;
for(int i = 0; i < 80; i++){
(*tx)= ~(*tx); //added this line
spi.transfer((unsigned char*) tx,(unsigned char*) rx, 2);
(*rx)= ~(*rx); //also added this line
printf("0x%04x\n", *rx);
pinControl.selectChip(i%8);
usleep(5);
}
before adding this there was nice clean output Data received:
0x04cb
0x04cb
0x04cb
0x04cb
0x04cb
0x04cb
0x04cb
0x050b
0x050b
0x050b
0x050b
After inverting:
0xfd36
0x02c9
0xfd36
0x02c9
0xfd36
0x02c9
0xfd36
0x02c9
0xfd36
0x02c9
0xfd36
0x02c9
0xfd36
0x02c9
Note the data I am sending is monotonically incrementing, so the second output is incorrect.
My hypothesis is
(*tx) = ~(*tx)
is not actually inverting the bits.
So I attempted to test this theory.
unsigned short* tx;
unsigned short* rx;
(*tx)=4;
std::cout << *tx << endl;
std::cout << ~(*tx) << endl;
(*tx) = ~(*tx);
std::cout << (*tx);
Yielded:
4
-5 <-- this is ~4 correct
65531 <-- this is unexpected