View Single Post
Old Mar 01, 2010, 10:40 PM
Teej is offline
Find More Posts by Teej
Registered User
Joined Feb 2010
59 Posts
Originally Posted by Dr Strangelove View Post

I assume the two lines ;

data[0] = i2c_read(1);
data[1] = i2c_read(0);

read two consecutive bytes of data. Does this mean that the data comming out of the sensors is 16bit?
Yes, this is to read 2 consecutive bytes. The '1' in the first _read specifies to ACK the receipt of the data byte. The '0' in the second implies not to ACK the second byte.

When the I2C master acks a read byte, it's an indication that it wants another byte. By sending the ACK, the slave loads up the next byte which the master will then clock in. (the master always controls the data clock).

Similarly, sending the STOP condition without ACKing a byte implies that the master has read all it cares to.

i2c_read and i2c_write are not exactly the names of functions I'm using, but it's close enough...and what you're using with the stamp will be different from what I'm using as well.

Yes, you're reading 2 bytes in, high byte first, and generating an unsigned int from it. One could read the first byte, multiply by 256, then add the second byte...but the math takes more cycles than reading the 2 bytes and then using a pointer.

Finally, I don't understand the line;
reading = *((USHORT *)(&data[0]));
* is a syntax for pointer, & means address. Lots of stuff in C is done more efficiently through the use of pointers and addresses.

Essentially what this means is:

*((USHORT *)(&data[0])) gives you the memory address of 'data'
*((USHORT *)(&data[0])) casts that address as a pointer to an unsigned 16 bit integer
*((USHORT *)(&data[0])) pulls out the integer that's being pointed to.

It is (drastically) more efficient than, but equivalent in function to:

reading = ((unsigned int)data[0] << 8) + (unsigned int)data[1]; ( << 8 means shift 8 bits to the left...iow, multiply by 256)


reading = ((unsigned int) data[0] * 256) + (unsigned int) data[1];

Is this just a means of coverting the two elements of the array to a 16 bit unsingned int by applying a 16bit mask?? In which case data[0] is the high byte? Is this the same as saying;

reading_high = 256 * data[0]
reading_low = data[1]

reading = reading_high + reading_low
Yes and no. That's the end result but it's not applying a mask.
Teej is offline Find More Posts by Teej
Reply With Quote