How to print the leading zero of HEX

I'm a beginner, I have this script to send and receive Hex from a hardware device. The reply that I've receive is in Hex but doesn't print the leading zero. For example it should print E2 00 00 16 60 10 02 27 18 20 5A 76 but it just printed E2 0 0 16 60 10 2 27 18 20 5A 76
Can someone help me?Thanks

#include "Arduino.h"

//#define DEBUG
unsigned char incomingByte;

void sendIdentifyCmd ()
{
  Serial1.write (0xbb);    
  Serial1.write (0x00);
  Serial1.write (0x22);  
  Serial1.write (0x00);                  
  Serial1.write (0x00);                  
  Serial1.write (0x22);
  Serial1.write (0x7e);              
#ifdef DEBUG
  Serial.print (0xbb);
  Serial.print (0x00);
  Serial.print (0x22);
  Serial.print (0x00);
  Serial.print (0x00);
  Serial.print (0x22);
  Serial.print (0x7e);
  Serial.println ();
#endif
}

void setup ()
{
  Serial.begin (115200);
  Serial1.begin (115200);
  Serial.println ("begin initial Serial!\n");
}

void loop ()
{
  sendIdentifyCmd ();
  delay (2);
  while(Serial1.available () > 0)
  {
      incomingByte=Serial1.read ();
      Serial.print (incomingByte,HEX);
      Serial.print (' ');
  }
  Serial.println ();
  delay (1000);
}

If the incoming byte is less than 10 (0x0A) print a "0" and then print the incoming byte.

groundFungus:
If the incoming byte is less than 10 (0x0A) print a "0" and then print the incoming byte.

I've tried this, and it printed 0E2 00 00 016 060 010 02 027 018 020 05A 076

It's not 10 (0x0A) but 16 (0x10) if you want to print the hexadecimal text representation.

byte x = 0x00;
byte y = 0x15;
if ( x <0x10)
{
  Serial.print("0");
}
Serial.println(x);

if ( y <0x10)
{
  Serial.print("0");
}
Serial.println(y);
1 Like
/*
   Demo of formatting hex numbers
*/
void setup ()
{
  Serial.begin(115200);
  Serial.println();

  int numbers[] = {226, 0, 0, 22, 96, 16, 2, 39, 24, 32, 90, 118};  //12 numbers
  int numNumbers (sizeof(numbers) / sizeof(int));                   //array size

  char buffer [3];
  for (int i = 0; i < numNumbers; i++) {
    if (numbers[i] < 10) Serial.print(F("0"));
    sprintf(buffer, "%x", numbers[i]);
    Serial.println (buffer);
  }
}

void loop ()
{
}

sterretje:
It's not 10 (0x0A) but 16 (0x10) if you want to print the hexadecimal text representation.

byte x = 0x00;

byte y = 0x15;
if ( x <0x10)
{
 Serial.print("0");
}
Serial.println(x);

if ( y <0x10)
{
 Serial.print("0");
}
Serial.println(y);

Thanks so much it's work properly

This topic was automatically closed 120 days after the last reply. New replies are no longer allowed.