I have an SPI chip that I would like to read out with an Arduino. Some of the registers are signed int others are unsigned int. I am writing a function to read any register.
A simplified version:
readRegister(byte thisRegister, char type) { if(type == 's'){ signed int result; }else{ unsigned int result; } // take the chip select low to select the device: SPI.beginTransaction(SPISettings(2500000, MSBFIRST, SPI_MODE3)); digitalWrite(SlaveSelectPin, LOW); //now get the value result = SPI.transfer16(thisRegister); // finish up digitalWrite(SlaveSelectPin, HIGH); SPI.endTransaction(); // return the result: return (result); } readRegister(0x4B87,'s') //read signed int register readRegister(0xB357,'u') //read unsigned int register However this doesn't work since the variable result is created inside the if statement so the scope is wrong. I get error: 'result' was not declared in this scope on the SPI.transfer() line.
How to solve this?
readRegisterandreadRegisterSigned. Alternatively, since SPI.transfer only returns an 8 bit value, and int is 16 bit, you could just use signed int for both returned values.SPI.transfer16, my mistake. It seems like a horrible waste of repeating code to write 2 allmost identical functions (the real function has more lines). Could I return the result assigned longno matter what the original type was?signed int readRegisterSigned(byte thisRegister){return (unsigned int)readRegister(thisRegister);}. Or just typecast at the calling end. I.e.(unsigned int)readRegister(0x4B87,'s');result,I return that from my functionreadRegisterand I cast that return to unsigned again, but then I return it from a function that yields a signed int. And it gives me the correct value? In what steps is the value actually changing?(uint8_t)signedVariable, you are really telling the complier: "trust me on this: signedVariable's value is really 8-bit unsigned".