-2

This is Arduino code, but since it uses C syntax, and it's not Arduino-specific, I thought I'd ask here. I have a few values defined so:

#define PID_RPM 0x0C

Typically it's used as a hex number. But in one spot, I need to print the last 2 chars ("0C") as literal 2 ASCII chars "0C". Right now I do it with a switch and an explicit string "0C":

switch(pid){
  case PID_RPM: OBD.println("0C"); break;
  ...

How can I convert the PID_RPM define to get its last 2 chars as literal ASCII? Maybe, instead of using a define, use char variables to store the hex PID values, then format them as a string with sprintf?

MrSparkly
  • 99
  • 3

1 Answers1

0

The # operator inside of a function-like macro will turn the argument into a string. If you do this twice, you can turn the macro expansion of the argument into a string:

#include <stdio.h>

#define MACRO_TO_STR(x) #x
#define EXPANSION_TO_STR(x) MACRO_TO_STR(x)
#define PID_RPM 0x0C

int main()
{
  printf("MACRO_TO_STR(PID_RPM) = %s\n", MACRO_TO_STR(PID_RPM));
  printf("EXPANSION_TO_STR(PID_RPM) = %s\n", EXPANSION_TO_STR(PID_RPM));
}

Here is the output:

MACRO_TO_STR(PID_RPM) = PID_RPM
EXPANSION_TO_STR(PID_RPM) = 0x0C
TallChuck
  • 142
  • 4
  • Thanks, sounds good. Can the expansion do a substring, too, i.e. get just the last two chars (the actual meaningful hex values)? – MrSparkly Mar 22 '22 at 06:21
  • @MrSparkly, the macro expansion cannot create substrings. But if you want to print the value in hex, you can just use `printf("%02X", PID_RPM);`. – Bart van Ingen Schenau Mar 22 '22 at 07:40
  • @BartvanIngenSchenau Thanks, everything works. – MrSparkly Mar 22 '22 at 09:52
  • the macro expansion creates a string literal, so yes, you can access a substring of that string. For a simple case like this, yes `printf` is probably a better option – TallChuck Mar 22 '22 at 15:14