mrUnfused
mrUnfused

Reputation: 45

pass macro definition to function taking reference as an argument

How can we pass a #defined macro to the function as an argument where the function accepts reference.

This is what I am trying the wrong way:

#define RST_REQ_REG 0x04
#define RESET_CMD   0x01

write_register(RST_REQ_REG, RESET_CMD, 1);


// Decleration of write_reg is
void write_register(uint8_t regAddr, uint8_t *writeByte, uint8_t writeByteLen);

Thanks !

Upvotes: 0

Views: 1742

Answers (2)

ThomasH
ThomasH

Reputation: 1165

Since you have to pass a pointer to the write_register function, you have to assign it to a variable first so it gets allocated storage. It cannot be passed as a literal. Why write_register takes a pointer is probably if you want to write more than one byte, so you can pass an array (an array in C is just a pointer to the first element of the array), but if you always want to write 1 byte it can get annoying.

So you need to do something like this:

uint8_t byteToWrite = RESET_CMD;
write_register(RST_REQ_REG, &byteToWrite, 1);

If this happens a lot and annoys you, you can write a wrapper function:

static void my_write_register(uint8_t regAddr, uint8_t writeByte)
{
  write_register(regAddr, &writeByte, 1);
}

Then you can call it like this:

my_write_register(RST_REQ_REG, RESET_CMD);

Upvotes: 1

Jabberwocky
Jabberwocky

Reputation: 50775

You can't. write_register accepts a pointer as second argument, period.

You probably want this:

#define RST_REQ_REG 0x04
#define RESET_CMD   0x01

uint8_t cmdbuffer[1] = {command};

write_register(RST_REQ_REG, cmdbuffer, 1);

Maybe you want to wrap this into another function:

void write_command(uint8_t regAddr, uint8_t command)
{
   uint8_t cmdbuffer[1] = {command};
   write_register(regAddr, cmdbuffer, 1);
}

...
write_command(RST_REQ_REG, RESET_CMD);

Upvotes: 2

Related Questions