Hi guys, I've come across two issues with sprintf outputting expected ascii characters. Check out the following code:
#include <stdio.h>
word outputVal;
char outputValChar[5]; /* char storage array */
void setup() {
Serial.begin(57600);
}
void loop()
{
if (Serial.available()) {
byte mode = Serial.read();
if (mode == 0x00)
sprintf(outputValChar, "%01c", 0x0000); /* This should output 0x00 */
else if (mode == 0x01)
sprintf(outputValChar, "%01c", 0x0001); /* This outputs 0x01 */
else if (mode == 0x02)
sprintf(outputValChar, "%02c", 0x0000); /* This should output 0x0000 */
else if (mode == 0x03)
sprintf(outputValChar, "%02c", 0x0001); /* This should output 0x0001 */
Serial.print(outputValChar);
}
}
You will need to be using a terminal that allows you to send and receive hex or this example will end up being pretty useless. What happens when this code is run is this:
mode 0x00, the format mask is telling the Arduino to pad with Zeroes, and output one character with a value of 0x0000. The actual result is that the Arduino does not output anything.
mode 0x01, the format mask is telling the Arduino to pad with Zeroes, and output one character with a value of 0x0001. The actual result is as expected - the Arduino outputs one character with the correct corresponding hex value.
mode 0x02, the format mask is telling the Arduino to Pad with Zeroes and output two characters with a value of 0x0000. The actual result is really weird here - the Arduino outputs the value 0x20 for the first character and then no other characters to represent the second character.
finally, mode 0x03, the format mask is telling the Arduino to Pad with Zeroes and output two characters with a value of 0x0001. The actual result is also weird here - the Arduino outputs the value 0x20 for the first character and then the correct hex code for the second value, too. Now, this doesn't actually work as expected - the Format mask is "%02C" which should pad the value 0x0001 with Zeros. Instead, the Arduino is changing the high byte of the value into 0x20.
Now, I understand that 0x20 is the ASCII representation for a space, but the format mask in all instances is telling sprintf to pad the values with Zeroes. That's not happening in most cases. Why not?
Also, if the value passed to sprintf is 0x0000 (or 0x0 or 0x00 if you modify the code above), then why does sprintf not return anything at all (not even 0x20) when the format mask defines 1 as the number of characters to return?
And no, I can't just use Serial.print(value, BYTE) - even if the value is 0x0001 - I should be able to return the equivalent as a character string (which would be 2 characters long.)
Any help with this would be great - thanks guys.