Arduino: Get EPC into a char array

I’m still learning how to write decent code in C++ and I really can’t get my head around how to get the epc value into a char array.

Specifically this is the part of the code that has been bugging me for quite a few hours by now:

for (byte x = 0 ; x < tagEPCBytes ; x++)
      {
        int cursorOffsetX = 6 * 3 * 2; //6 pixels of size 3 two digits
        int y;
        
        if (rfidModule.msg[31 + x] < 0x10){
          Serial.print(F("0")); //Pretty print
          tft.setCursor(x * cursorOffsetX, 40);
          tft.print("0");
          y = x * cursorOffsetX + (cursorOffsetX/2);
        } 
        else{
          y = x * cursorOffsetX;
        }
 
        Serial.print(rfidModule.msg[31 + x], HEX);
        Serial.print(F(" "));
        tft.setCursor(y, 40);
        tft.print(rfidModule.msg[31 + x], HEX);

      }

      Serial.print(F("]"));
      Serial.println();

I have added some logic to output the result to my display, but it’s a bit cumbersome having to calculate the position of the cursor (especially if I want to change the font size down the line). Instead I wanted to just put alle of the strings into a variable and output that at once. But how do I populate a char array instead correctly? I have tried sprinf to convert the hex value from the msg, but that didn’t go well (got a lot of jibberish on the display).

I’m sure it’s quite an easy question to answer I just cant seem to get my head around it :frowning:

Alright I’ve finally figured it out :sweat_smile:

The key was to use sprintf and the %X and now it’s working as expected!

      char epcHex[30];
      epcHex[0] = '\0';
      for (byte x = 0 ; x < tagEPCBytes ; x++)
      { 
        if ((x % 2 == 0) && (x != 0)){ //Add - between every 4 digits
          strcat(epcHex,"-");
        }     
        if (rfidModule.msg[31 + x] < 0x10){
          Serial.print(F("0")); //Pretty print
          strcat(epcHex,"0");
        } 
 
        Serial.print(rfidModule.msg[31 + x], HEX);
        Serial.print(F(" "));

        char buf[5];
        sprintf(buf, "%x", rfidModule.msg[31 + x]);
        strcat(epcHex,buf);
      }

      strcat(epcHex,'/0');
      Serial.print(F("]"));
      tft.setCursor(0, 40);
      tft.setTextSize(2);
      tft.print(epcHex);

1 Like