Is there a way to get Serial.print to print out the whole of a variable as binary- with leading zeros so that the message is always the same length of characters. I've been trying with sprintf, but the only way I've got close is as below
This gives a binary number in the right position on the serial monitor, but without 0s, just blank space (my understanding of the syntax for sprintf is that the 0 before the 16 tells sprintf to pack 0's at the beginning of the string to make it 16 chars long.
I realise this is probably a daft way to go about it - but I can't see a simpler method.
BTW, I think for the first version, you want to pass the int (sensor) straight to the sprintf() to get it to be zero-padded - I think you can only get space-padding if you're printing a string.
Yeah I had a version working like that - but wanted a binary version and couldn't see a way to get sprintf to convert to binary itself - that was why I was passing it between those two buffers.
Then I realised I was being silly doing it that way.
Maybe something like the following, based on your use of sprintf for the binary conversion:
//
// davekw7x
//
void setup()
{
Serial.begin(9600);
}
int Sensor = 0;
char buffer[17];
void loop()
{
Sensor++;
// Convert to binary number as a "string" so that we can know
// how many significant bits there are
itoa (Sensor, buffer, 2);
// Loop to print leading zeros
for (int i = 0; i < 16-strlen(buffer); i++) {
Serial.print('0');
}
// Now print the significant bits
Serial.println(buffer);
delay(1000);
}
Or, you can print the bits, one at a time, without all of the sprintf stuff (and without unnecessarily invoking floating point math functions):