Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to `Serial.print()` "full" hexadecimal bytes?

I am programming Arduino and I am trying to Serial.print() bytes in hexadecimal format "the my way" (keep reading for more information).

That is, by using the following code

byte byte1 = 0xA2;
byte byte2 = 0x05;
byte byte3 = 0x00;

Serial.println(byte1, HEX);
Serial.println(byte2, HEX);
Serial.println(byte3, HEX);

I get the following output in the Serial Monitor:

A2
5
0

However I would like to output the following:

A2
05
00

In words, I would like to print the "full" hexadecimal value including 0s (05 instead of 0 and 00 instead of 0).

How can I make that?

like image 546
Backo Avatar asked Oct 01 '13 23:10

Backo


3 Answers

Simple brute force method, is to write a routine as:

void p(char X) {

   if (X < 16) {Serial.print("0");}

   Serial.println(X, HEX);

}

And in the main code:

p(byte1);  // etc.
like image 159
JackCColeman Avatar answered Nov 02 '22 02:11

JackCColeman


sorry - not enough reputation to comment but found previous answer is not fully correct. Actually, the nice light way to code it should be :

void p(byte X) { if (X < 10) {Serial.print("0");} ...

giving the code:

void p(byte X) {

   if (X < 10) {Serial.print("0");}

   Serial.println(X, HEX);

}

And in the main code:

p(byte1);  // etc.

hope this helps

like image 39
G1l0uX Avatar answered Nov 02 '22 03:11

G1l0uX


Use sprintf to print into a buffer (two chars per byte + null terminator):

byte byte1 = 0xA2;
byte byte2 = 0x05;
byte byte3 = 0x00;
char s[7];
sprintf(s, "%02x\n%02x\n%02x", byte1, byte2, byte3);
Serial.println(s);

Added new lines in between to get each on new line. About '%02x', the % means here comes formatting information, 0 means to pad with 0, 2 means pad input until 2 characters wide and x means give me this as hexadecimal.

For other formatting options see http://linux.die.net/man/3/sprintf

like image 31
thoredge Avatar answered Nov 02 '22 01:11

thoredge