Please help me understand 2 things I found in this C code:
First, there is the whole code:
usbMsgLen_t usbFunctionSetup(uchar data[8])
{
usbRequest_t *rq = (void *)data;
static uchar dataBuffer[4]; /* buffer must stay valid when usbFunctionSetup returns */
if(rq->bRequest == CUSTOM_RQ_ECHO){ /* echo -- used for reliability tests */
dataBuffer[0] = rq->wValue.bytes[0];
dataBuffer[1] = rq->wValue.bytes[1];
dataBuffer[2] = rq->wIndex.bytes[0];
dataBuffer[3] = rq->wIndex.bytes[1];
usbMsgPtr = dataBuffer; /* tell the driver which data to return */
return 4;
}else if(rq->bRequest == CUSTOM_RQ_SET_STATUS){
if(rq->wValue.bytes[0] & 1){ /* set LED */
LED_PORT_OUTPUT |= _BV(LED_BIT);
}else{ /* clear LED */
LED_PORT_OUTPUT &= ~_BV(LED_BIT);
}
}else if(rq->bRequest == CUSTOM_RQ_GET_STATUS) {
dataBuffer[0] = ((LED_PORT_OUTPUT & _BV(LED_BIT)) != 0);
usbMsgPtr = dataBuffer; /* tell the driver which data to return */
return 1; /* tell the driver to send 1 byte */
}
return 0; /* default for not implemented requests: return no data back to host */
}
Now, usbFunctionSetup
gets array of 8 unsigned chars. Now there comes the line:
usbRequest_t *rq = (void *)data;
So, I get the left side of the statement, but what is on the right? I know that (void *)
is cast to this type, but why?
And second question is, isnt this code inefficient? Because first function receives 8 bytes of data, and than it creates additional pointer to them. And that additional pointer is created, at least if I am right, just to be able to access individual data by its name defined in usbRequest_t
struct. Wouldn't be simpler and more efficient to just use in code instead of rq->bRequest == something
just for example
data[2]==something
or if bRequest
is bigger than one byte, for example data[1] == low_byte_of_something && data[2]== high_byte_of_something
?
Thanks.