logitech mouse logitech mouse - 1 month ago 11
C Question

Passing struct members to function in c

I have a

struct
defined below for the contents of a frame to be sent over uart.

The last member of the struct is a frame check sequence (fsc) that is computed as an XOR of all the bytes in the struct members(len, cmd0, cmd1 and data). I have a function to calculate the fsc below.

My question is, how would I go about passing the struct members to
calcFCS()
which is called in
build_uart_frame()
?

Many thanks

typedef struct uart_frame {
uint8_t sof; /* 1 byte */
uint8_t len; /* 1 bytes */
uint8_t cmd0; /* 1 byte */
uint8_t cmd1;
char data[11]; /* 0 -250 byte */
unsigned char fcs; /* 1 byte */
} uart_frame_t;

//-------------------------------------------------------------------------

// Global uart frame
uart_frame_t rdata;

//-------------------------------------------------------------------------
unsigned char calcFCS(unsigned char *pMsg, unsigned char len) {

unsigned char result = 0;
while(len--) {
result ^= *pMsg++;
}

return(result);
}

//-------------------------------------------------------------------------

// Worker code to populate the frame

int build_uart_frame() {

uart_frame_t *rd = &rdata; //pointer variable 'rd' of type uart_frame

// common header codes
rd->sof = 0xFE;
rd->len = 11;
rd->cmd0 = 0x22;
rd->cmd0 = 0x05;
snprintf(rd->data, sizeof(rd->data), "%s", "Hello World");
rd->fcs = calcFCS(?)
return 0;
}

Answer

As you says

a frame check sequence (fsc) that is computed as an XOR of all the bytes in the struct members(len, cmd0, cmd1 and data)

Instead of passing all member separately,better you pass pointer to struct uart_frame

So signature of your function should be

unsigned char calcFCS(uart_frame* frame)

Comments