Monday, November 29, 2010

Schrodenger's Computer

I was working on writing a Modbus Communication Driver for the 7395 and ran into some interesting behavior.

The device I needed to communicate with used the binary style protocol with CRC. This of course means that your data payload can and will have Null chars 0x00. Unfortunately, C/C++ functions that deal with strings or arrays of char will treat the first 0x00 as the end of the data and terminate at that point regardless of the actual size of the string.

At first, I wrote my own functions to ignore null chars by using a length parameter. This seemed to work well enough but I noticed that the data going over the port wasn't always right. Specifically, if I printed the chars with printf (using %x for each character), the data would be as expected. If I did not use printf I would get data that was consistently not what I was loading into the array.

It appeared that by observing the data I could affect it's content!

It actually turns out that this is true. The reason is that the %x argument in my printf (used to print a variable in hex format) was doing an in place cast from char to unsigned integer, thus if I did printf then broadcast the data it would be transmitted as expected.


I wound up reimplementing most of my code to use an array of integer in the first place to avoid this problem but still who would have thought?

No comments:

Post a Comment