-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?

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
  • 152