Can't use enum as function argument

I did not experience the problem because I usually use a Makefile instead of the Arduino IDE. I now tried with the IDE version 1.0.5 and I had the same problem as you. The fix is to explicitly declare the function before defining it:

void Move(Dir direction, int distance);
void Move(Dir direction, int distance)
{
     direction = forward;
}

The Arduino 1.7.x series from Arduino.org uses the old build system that is severely broken when you try and do anything more complex than simple types.

It adds prototypes to your functions to the top of the program so you don't have to get the order right, but it puts them in completely the wrong place. The result is a C++ file that looks like this:

#include <Arduino.h>
void Move ( Dir direction , int distance );
void setup();
void loop();

enum Dir
{
  forward = 1,
  backward = 2,
  left = 3,
  right = 4
};

void Move ( Dir direction , int distance )
{
     direction = forward;
}

void setup() {
  // put your setup code here, to run once:
}

void loop() {
  // put your main code here, to run repeatedly:
}

As you can see the prototype involving Dir has been placed before the definition of Dir, and so it fails miserably.

There are some hacks you can do to force it to place the prototypes after your definition, but I can't recall what they are off hand.

The simple answer is to ditch Arduino 1.7.10 and switch to Arduino 1.6.10 from Arduino.cc instead. This uses the Arduino Builder system which does things much better, including placing the prototypes in the right place.

Despite the numbering 1.7.10 is not a newer version than 1.6.10 - it is an older version renumbered. It's all part of the schism between the two halves of Arduino.

Even better is to ditch the awful Arduino IDE entirely and use one of the many far better IDEs that exist.


As Majenko points out, this seems to be a problem with the parsing of the preprocessor.

You have two options:

  • Use Edgar Bonets solution and declare the function before defining it
  • Create a separate header file for your enum in a new tab and import it with #include "[myEnumsHeaderFilename].h"
  • #include "myEnums.h"
    
    
    void Move(Dir direction, int distance)
    {
       direction = forward; 
    }
    
    void setup() {}
    
    void loop() {}
    

    Tags:

    Programming