Exploring Edison - I2C Measuring Temperature And Humidity |

Written by Harry Fairhead | ||||

Monday, 07 December 2015 | ||||

Page 3 of 3
## Checksum calculationAlthough computing a checksum isn't specific to I2C, it is another common task. The datasheet explains that the polynomial used is: X Once you have this information you can work out the divisor by writing a binary number with a one in each location corresponding to a power of X in the polynomial - i.e. the 8th, 5th, 4th and 1st bit. Hence the divisor is 0x0131. What you do next is roughly the same for all CRCs. First you put the data that was used to compute the checksum together with the checksum value as the low order bits:
Now you have three bytes, i.e 24 bits in a 32-bit variable. Next you adjust the divisor so that its most significant non-zero bit aligns with the most significant bit of the three bytes. As this divisor has a one at bit eight it needs to be shifted 15 places to the right to move it to be the 24th bit:
Now that you have both the data and the divisor aligned, you step through the top-most 16 bits, i.e. you don't process the low order eight bits which is the received checksum. For each bit you check to see if it is a one - if it is you replace the data with the data XOR divisor. In either case you shift the divisor one place to the right:
When the loop ends, if there was no error, the data32 should be zeroed and the received checksum is correct and as computed on the data received. A complete function to compute the checksum with some optimizations is:
It is rare to get a crc error on an I2C bus unless it is overloaded or subject to a lot of noise. ## The Complete ProgramThe complete program including crc checks is:
Of course this is just the start. Once you have the device working and supplying data it is time to write your code in the form of functions that return the temperature and the humidity and generally make the whole thing more useful and easier to maintain. This is often how this sort of programming goes - at first you write a lot of inline code so that it works as fast as it can then you move blocks of code to functions to make the program more elegant and easy to maintain checking at each refactoring that the programming still works.
## Where NextThe I2C bus is useful, but there are are other less standard buses that prove to be useful for one off devices. In the next chapter we look at the first problem we have to solve - working with 1.8V logic. The problem is that while there might be 1.8V I2C devices other less standard buses tend to work at 5V or 3.3V. So before moving on it is worth spending some time looking at how to inter-work 1.8V with 5V and 3.3V logic.
You can now buy a print edition of Exploring Intel Edison. |
||||

Last Updated ( Saturday, 27 February 2016 ) |