I am trying to display a byte coming from an I2C slave in a binary form.
If I display the byte in decimal form it works:
i2c_start_wait(device_write_address); // set device address and write mode
i2c_write(0x08); // read address
i2c_rep_start(device_read_address); // set device address and read mode
char statusBuffer[25];
sprintf(statusBuffer, "Chip status : %i", i2c_readNak());
Serial.println(statusBuffer);
i2c_stop();
The terminal displays this text: "Chip status : 132", which is correct for that I2c device.
However with this code:
i2c_start_wait(device_write_address); // set device address and write mode
i2c_write(0x08); // read address
i2c_rep_start(device_read_address); // set device address and read mode
char statusBuffer[25];
sprintf(statusBuffer, "Chip status : %08b", i2c_readNak());
Serial.println(statusBuffer);
i2c_stop();
the terminal displays
"Chip status : " with no value afterwards althought I'd like to see "Chip status : 10000100"
What's wrong ?
system
June 13, 2011, 10:22am
2
sprintf(statusBuffer, "Chip status : %08b", i2c_readNak());
I don't see b listed as a valid output type in my book, or here:
http://www.cplusplus.com/reference/clibrary/cstdio/sprintf/
system
June 13, 2011, 10:28am
3
You could print the value in hex.
Hex to binary is easy to do in your head, decimal to binary isn't quite so simple.
I have tried this function but I got an "invalid conversion from 'const char*' to 'char' " error message.
//byte to binary string conversion
char byte_to_binary(int x) {
char binaryString[8];
for (int i = 0; i < 8; i++) {
if ((x && pow(2, i)) == 1) {
binaryString[7-i] = "1";
} else {
binaryString[7-i] = "0";
}
}
}
system
June 13, 2011, 11:50am
5
binaryString[7-i] = '1';
Your char function has no return statement.
I don't recommend the use of "pow" for simple integer powers of two.
If you're not happy with masks and shifts, use "bitRead"
I am ok with masks and shifts but rather confused with char vs char*. bitRead is fine, I decided to convert each bit on the fly without storing data in a string, it's for display purposes only anyway.
Thanks for the advice.
system
June 13, 2011, 2:46pm
7
but rather confused with char vs char*.
You had a "char" array element, but you were trying to assign it a string - double quotes " implies string, and a string needs a char pointer (char*)
You should have been using single quotes, as I pointed in my earlier post, to assign a single char.