Help. I need a debug macro

I've seen some of you guys use some pretty ingenious macros to print variable names with values and stuff like that. Has anyone got anything that will do this for registers:

void printRegs(){
  volatile uint32_t mstpcrc = R_MSTP->MSTPCRC;
  Serial.print("MSTPCRC : ");
  Serial.println(mstpcrc , HEX);

  volatile uint32_t cacr0 = R_CAC->CACR0;
  Serial.print("CACR0 : ");
  Serial.println(cacr0 , HEX);

  volatile uint32_t cacr1 = R_CAC->CACR1;
  Serial.print("CACR1 : ");
  Serial.println(cacr1 , HEX);

  volatile uint32_t cacr2 = R_CAC->CACR2;
  Serial.print("CACR2 : ");
  Serial.println(cacr2 , HEX);

  volatile uint32_t caicr = R_CAC->CAICR;
  Serial.print("CAICR : ");
  Serial.println(caicr , HEX);

  volatile uint32_t callvr = R_CAC->CALLVR;
  Serial.print("CALLVR : ");
  Serial.println(callvr , HEX);

  volatile uint32_t caulvr = R_CAC->CAULVR;
  Serial.print("CAULVR : ");
  Serial.println(caulvr , HEX);

  volatile uint32_t cacntbr = R_CAC->CACNTBR;
  Serial.print("CACNTBR : ");
  Serial.println(cacntbr , HEX); 

}

I want something where I can replace each set of three lines there with just:

PRINT_REG(R_MSTP->MSTPCRC);
or
PRINT_REG (R_CAC->CACNTBR);

And have it print the register name along with the value in hex. I don't mind if it prints the whole register name with the arrow and all but I'd prefer to just see the last part that is the actual name of the register.

#define PRINT_REG(BUCKET,REGISTER) \
do { \
  uint32_t t = BUCKET->REGISTER; \
  Serial.print( #REGISTER " : "); \
  Serial.println(t , HEX); \
} while (false)

Comma instead of arrow...
PRINT_REG(R_MSTP,MSTPCRC);

The volatile serves no useful purpose for locals.

1 Like

Awesome thanks. I'll test tonight but I'm sure it's good.

May I ask, why the do-while(false) business? I knew there would be some piece like that I would miss. That's why I asked the forum.

Please do educate me on that one if you don't mind.

1 Like

It's a safety net. This looks like a good explanation. Basically, it makes the macro behave like a function call.

If you use braces with all your control structures (if, while, etc.) then I don't think the do + while makes a difference. At least I cannot think of any other use.

The nested scope keeps t from conflicting with anything else.

1 Like

Tested and works like a charm. Thanks for that.

1 Like

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