Struct and functions when using the Arduino IDE

As anyone reading this blog probably knows, the Arduino IDE simplifies a number of programming for an embedded environment and hides some of the required C / C++ material. This can make life a lot easier, but it can also cause problems, especially when you step out to do more complex things. I got bit by one of those earlier today. Since I eventually found a post to the work around, I thought I’d post it here.

In my robot code, I”ve defined a struct called coord that holds two doubles, which are the x and y coordinates for whatever I need (e.g., the position of the robot, the next waypoint, etc.

Today, I wanted to compute the distance from the ray defined by the previous and next waypoint and the current position of the vehicle, so that the error could be fed into a PID controller. I figured it would be easy to pass the parameters as coord types. BUT, this turns out to be trickier than it should be with the Arduino. Unless the structs are defined in a .h file, there are problems with their scope. A work-around is documented by Alexander Brevig on the Arduino Playground: Struct Resource for Arduino.

One thought on “Struct and functions when using the Arduino IDE

  1. I fought with this for awhile. Ended up not needing the .h file. I declared the struct and struct variables globally before setup() but the compiler was super particular about declaration. The following worked for me and I subsequently passed the struct variables between functions and used their member values successfully.

    struct Steppr{ //avoids “Stepper” class name
    int stepPin;
    int dirPin;
    int enablePin;
    long pos;
    }; //could not declare variables here after closing curly-brace

    Steppr stepperA = {46, 48, 62, 10000}; //Could not declare the variable name and
    Steppr stepperB = {54, 55, 38, 10000}; //then assign values with dot operator,
    //but this worked.

    digitalWrite(stepperA.enablePin, LOW); //active low
    …more setup stuff…

    loop() {
    moveTo(12000, stepperA);
    stepperA.pos = 12000;
    …do more stuff…
    moveTo(9000, stepperB);
    stepperB.pos = 9000;
    …do more stuff…

    moveTo(long there, Stepper s){
    while(s.pos<there) {
    …make it go…

Leave a Reply

Your email address will not be published. Required fields are marked *