We are about to switch to a new forum software. Until then we have removed the registration on this forum.
I am using the following code [snipit] to read a temp sensor:
i2c.beginTransmission(addr);
i2c.write(0x0E);
byte[] in1 = i2c.read(2);
byte lowerLevel1 = in1[0];
byte upperLevel1 = in1[1];
int temperature1 = ((upperLevel1<<8) | lowerLevel1);
if (temperature1 > 2047) {
temperature1 = temperature1 - 4096;
}
So, am having an issue with the result (random negative values)!
I ported (if this is the correct terminology) the code below:
// convert the upper byte of the 12bit signed value into proper 16bit signed
// format, if value is negative
if (tmp & 0b00001000) tmp |= 0b11111000;
// construct the 16bit signed value, shifting the upper byte 8 bits up and adding
// the lower byte
raw = (tmp << 8) | rxBuffer[0];
I believe the problem may be the use of "int" a 32 bit register . . . whereas this shifting is 16 bit?
Can someone confirm this or spot an issue in my conversion to Processing.
Thanks in advance . . .
Answers
I suggest masking your read values, lines 4 and 5. Example :
This ensures others unwanted bits are set to zero. Then convertion would always provide positive values.
Kf
That does not work . . . Type mismatch int with byte.
Hmmm then btw line 6 and 7 do
Kf
You can use
short
data type.http://cs.fit.edu/~ryan/java/language/java-data.html
@Lord a short might not work if he is on a 64 bit machine. He should mask the new generated number.
Kf
For what it is worth . . . Processing is running on the Rpi 3
BTW - I was looking for uint16_t . . . I did not see short in the Processing reference, I will try and use anyway.
short
is the most prejudiced primitive datatype (there are 8) in Processing! >:PIt's amazing how they list 7, but censor the existence of
short
! @-)Complete primitive datatype list btW: :P
http://docs.Oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
@kfrajer What? I'm on a 64-bit machine (not now, but I use one for programming) and short has been working for me.