cvariablesroboticsrobotc

How to make what function I use in c be controlled by a variable


This is my first year of vex. I am taking on the role of programmer. I have had this idea for rapid autonomous creation, recording the driver. Instead of the usual array/debugger dump of raw streams of power levels, I had the idea of extracting functions from driver movement. I wont go into the details, and I can code it myself, but I need some help.

There is one thing I am unable to do simply because of my lack of coding experience.

I want to create a for loop that checks every joystick button one by one.

For example:

struct button
{
    bool pressed;
}

for(int i = 0; i>12; i++) //12 is number of buttons on the joystick
{
    struct button button<cycle through buttons>;
}

I want there to then be:

struct button button6U;
struct button button6D;
struct button button6R;
etc.

Then, I want this:

for(int i = 0; i>12; i++) // 12 is number of buttons on the joystick
{
    if(VexRT[<currentButton>])
    {
        button<currentButton>.pressed = true;
    }
}

I have no idea how to do this, with a wildcard modifing the actual variable name I am writing to.

A couple thoughts: A for statement would have no idea how to advance the order of joystick buttons. So something I think I might need is:

orderOfButtons
{
    VexRT[6U];
    VexRT[6D];
    VexRT[6R];
    // etc.
}

I just cant seem to figure out how to have a variable defining what VexRT[]button I am reading from.

Any help would be appreciated! Thanks.


Solution

  • Sounds like you want an array:

    #define NUMBER_OF_BUTTONS 12
    ...
    struct button VexRT[NUMBER_OF_BUTTONS];
    

    If you want to use symbolic constants to refer to specific buttons in the array, you can use an enumeration:

    enum btn_id { BTN_6U, // maps to 0
                  BTN_6D, // maps to 1
                  BTN_6R, // maps to 2
                  ...
                }
    

    Enumeration constants are represented as integers, and by default they start at 0 and increment by 1. You can initialize them to different values if you want, and multiple enumeration constants can map to the same value. I take advantage of this when I want to identify a "first" and "last" enumeration for looping, like so:

    enum btn_id {
      BTN_6U,
      BTN_FIRST = BTN_6U, // both BTN_FIRST and BTN_6U will map to 0
      BTN_6D,
      BTN_6R,
      ...
      BTN_whatever,
      BTN_LAST        
    };
    

    Thus, VexRT[BTN_6U] maps to VexRT[0], VexRT[BTN_6D] maps to VexRT[1], etc.

    Note that this way, you don't have to loop through all the buttons just to set one:

    enum btn_id currentButton = BTN_6D;
    ...
    VexRT[currentButton].pressed = true;
    

    If you do want to loop through the whole set, you can use

    for ( enum btn_id i = BTN_FIRST; i < BTN_LAST; i++ )
    {
      VexRT[i].pressed = false;
    }