The most efficient way to use different structure elements in a function?

I am writing for a very limited resource embedded processor. I have a structure that captures the time series of events, and I would like to use the same graphic display function for different values โ€‹โ€‹of different types. Something like (very stripped down, do not sweat uninitialized values, etc.):

#define GRAPH_ONE 1 #define GRAPH_TWO 2 struct _event_t { unsigned long timestamp; int sensorOne; float sensorTwo; } typedef struct _event_t event_t; event_t[10] MyEvents; void GraphSensor(byte graphType) { for (unsigned int i = 0; i < 9; i++) { // Get minimum value from series if (MyEvents[i].?????) ... } } 

How can I use my function for different members of the structure? I can see this with a ton of switch (graphType) statements, but it's pretty ugly. There can easily be 8 or 10 members of the structure. I could move all these functions to a separate function and make each data access bit this function, always returning a float (which should be OK for my graph). Finally, I can convert to C ++ classes, which opens up other tools.

None of them are feeling well. Is there a better approach, preferably very light?

+6
source share
2 answers

You can wrap the accessory that you need in the function and pass it to the function, which moves the array and aggregates the results. for instance

 float getSensor1(const event_t* t) { return t->sensorOne; } float getSensor2(const event_t* t) { return t->sensorTwo; } void GraphSensor(float (*accessor)(const event_t*)) { // Get minimum value from series float min_value = MAX_FLOAT; for (unsigned int i = 0; i < 9; i++) { float x = accessor(MyEvents + i); if (x < min_value) min_value = x; } } /* later on . . . */ GraphSensor(getSensor1); GraphSensor(getsensor2); 

You basically disconnect data access from operations on it and homogenize it all to floating ones. The aggregation operation can also be encapsulated in a function. But this is approaching a smaller map. :)

+6
source

You can change the structure to an array that uses, possibly, all floats. Thus, data processing is completely homogeneous.

 #define N_SENSORS 12 #define N_EVENTS 10 float MyEvents [N_EVENTS] [N_SENSORS]; void GraphSensor(byte graphType) { float min = 1e38; for (unsigned int i = 0; i < N_EVENTS; i++) { // Get minimum value from series if (MyEvents[i][graphType] < min) min = MyEvents[i][graphType]; } } 

Perhaps the timestamp can also be in element 0, possibly using tables: the integer part is days from 1970 or 1900, and the fractional part is part of the day (so noon = .5).

+3
source

Source: https://habr.com/ru/post/972349/


All Articles