Call functions numerically with pointers

You are storing the function pointers in PROGMEM and then accessing them as though they were stored in SRAM. That is not going to work well. Since the 3 pointers use a total of 6 bytes, I really can't understand why they can't live in SRAM.

I had no problem compiling and running your program with the suspicious calls uncommented. Are you sure that you have changed the serial speed in the monitor? My example was 115200 you use 9600(why?)

PaulS:
You are storing the function pointers in PROGMEM and then accessing them as though they were stored in SRAM. That is not going to work well. Since the 3 pointers use a total of 6 bytes, I really can't understand why they can't live in SRAM.

Apart from that, the example shouldn't have worked.

The pointers are in PROGMEM and it was called from non-PROGMEM. However the compiler came to the rescue and optimized the loop away:

 11a:	0e 94 12 01 	call	0x224	; 0x224 <_ZN14HardwareSerial5beginEm>
 11e:	0e 94 80 00 	call	0x100	; 0x100 <_Z5func1v>
 122:	0e 94 79 00 	call	0xf2	; 0xf2 <_Z5func2v>
 126:	0e 94 72 00 	call	0xe4	; 0xe4 <_Z5func3v>

Notice that the loop doesn't exist in the code?

So to make it really do what we want we have to prevent the optimization:

void (*Farr[])() PROGMEM  = {func1, func2, func3};

volatile int foo = 3;

void setup(){
  Serial.begin(115200);
  for(int i = 0; i < foo; i++) Farr[i]();
}//setup()

Now, the code fails to print anything, which is what you want. :wink:

I agree with PaulS that you hardly need to use PROGMEM here, but in case you were envisaging a much larger array, this works:

typedef void (* myFunction) ();

PROGMEM myFunction Farr []  = {func1, func2, func3};

volatile int foo = 3;

void setup(){
  Serial.begin(115200);
  for(int i = 0; i < foo; i++) 
    {
    myFunction f = (myFunction) pgm_read_word (&Farr [i]);
    f ();
    }
}//setup()

void loop(){}//loop()

void func1(){
  Serial.println(F("function1"));
}//func1()

void func2(){
  Serial.println(F("function2"));
}//func2()

void func3(){
  Serial.println(F("function3"));
}//func3()

A little strange. When trying nicks example i get this:

sketch_dec13a.ino:3: warning: only initialized variables can be placed into program memory area

When running this code:

void (*Farr[])() PROGMEM  = {FuncA, FuncB, FuncC};

volatile int foo = 3;

void setup(){
  union {
  void (*p)();
  int i;
  }cv;
  Serial.begin(115200);
  for(int i = 0; i < foo; i++){
    cv.p = Farr[i];
    Serial.println(cv.i);
  }
}//setup()

void loop(){}

void FuncA(){
  Serial.println("Function A");
}

void FuncB(){
  Serial.println("Function B");
}

void FuncC(){
  Serial.println("Function C");
}

i get this output:

0
514
514

This leads me to believe that despite that the addresses of the functions should be known at compile time the array is not initialized. Why??

nilton61, I used 9600 because I've known the serial monitor to crash when it receives large volumes of data. Your last example isn't using pgm_read_word, perhaps this is the problem.

Nick, accessing the compiled code is useful, how do you do that? Seems the optimiser is overstepping its responsibilities if it makes code work that would otherwise fail! Your code compiled fine for me. Packaging it into a macro and implementing it in my example gives the following, which now also works!

typedef void (* myFunction) ();
PROGMEM myFunction FunctionArray[] = {FuncA, FuncB, FuncC};
#define CallF(Num) ((myFunction) pgm_read_word (&FunctionArray [Num])) ()

byte Global;

void setup(){
  Serial.begin(115200);
  
  Global = 1;
  byte Local = 1;
  // Local = Global; // THIS NO LONGER SCREWS EVERYTHING UP
  
  // Global and Local display as expected:
  Serial.print("Global = ");
  Serial.println(Global);
  Serial.print("Local = ");
  Serial.println(Local);
  
  // These work fine:
  CallF(0);
  CallF(1);
  CallF(2);
  
  // These now work too!
  CallF(Local); // Calls FuncB
  CallF(Global); // Calls FuncB
  
  // For good measure so does this:
  for(byte a = 0; a <= 2; a++)
  {
    CallF(a);
  }
}

void loop(){}

void FuncA(){
  Serial.println("Function A");
}

void FuncB(){
  Serial.println("Function B");
}

void FuncC(){
  Serial.println("Function C");
}

Thanks for the advice!

As an aside, yes I'm using PROGMEM because I want the potential to handle much larger arrays of functions, and because storing constants in RAM just seems wrong to me!

paulrd:
Nick, accessing the compiled code is useful, how do you do that?

So everything allocated with the PROGMEM macro must be retrieved with pgm_read_xxxxx()?

I read this:

GCC has a special keyword, attribute that is used to attach different attributes to things such as function declarations, variables, and types. This keyword is followed by an attribute specification in double parentheses. In AVR GCC, there is a special attribute called progmem. This attribute is use on data declarations, and tells the compiler to place the data in the Program Memory (Flash).

AVR-Libc provides a simple macro PROGMEM that is defined as the attribute syntax of GCC with the progmem attribute. This macro was created as a convenience to the end user, as we will see below. The PROGMEM macro is defined in the <avr/pgmspace.h> system header file.

here:http://www.atmel.no/webdoc/AVRLibcReferenceManual/pgmspace_1pgmspace_introduction.html

A few pages down it says this:

Now that your data resides in the Program Space, your code to access (read) the data will no longer work. The code that gets generated will retrieve the data that is located at the address of the mydata array, plus offsets indexed by the i and j variables. However, the final address that is calculated where to the retrieve the data points to the Data Space! Not the Program Space where the data is actually located. It is likely that you will be retrieving some garbage. The problem is that AVR GCC does not intrinsically know that the data resides in the Program Space.

http://www.atmel.no/webdoc/AVRLibcReferenceManual/pgmspace_1pgmspace_data.html

Any reason why the compiler isnt aware of its own attribute keyword?

I believe C++ can distinguish types but not attributes.

nilton61:
So everything allocated with the PROGMEM macro must be retrieved with pgm_read_xxxxx()?

It is in a different memory space, so, yes.

I suspect in this case the attribute is applied by the linker rather than the compiler, in which case it would be reasonable for the compiler to be ignorant of its implications.

Thanks for the help everyone.

Part of what I'm hoping to do with this code is to move the functionality out of my Arduino projects and into an external '.h' include file. More on this here:
http://forum.arduino.cc/index.php?topic=201954.msg1488368#msg1488368

However when I try and move this line into my include file:

PROGMEM myFunction FunctionArray[] = {FuncA, FuncB, FuncC};

The compiler complains:

error: 'PROGMEM' does not name a type

Anyone know what might be causing this? My guess is that it's caused be a difference in the way Arduino code and C are handled, but I don't know how to 'translate' the above line to make it C-friendly.

Post code that demonstrates this. For example, zip up the whole project and attach that to a post.

your progmen.h file should look like this:

#include <arduino.h>
typedef void (* myFunction) ();
void FuncA(void);
void FuncB(void);
void FuncC(void);
PROGMEM myFunction Farr[] PROGMEM  = {FuncA, FuncB, FuncC};

Here's a zip file that demonstrates the problem. If you unzip it at the root of your C drive it should work. The main file is this:

//------------------------------------------------------------
// Option A: Set up locally: WORKS
typedef void (* myFunction) ();
PROGMEM myFunction Farr[] = {FuncA, FuncB, FuncC};
#define CallF(Num) ((myFunction) pgm_read_word (&Farr [Num])) ()

// Option B: Set up using external include - DOESN'T WORK
//#include "C:\Arduino\IncludeTest\Includes\Include.h"
//------------------------------------------------------------

byte Global;

void setup(){
  Serial.begin(115200);
  
  Global = 1;
  byte Local = 1;
  
  // Global and Local display as expected:
  Serial.print("Global = ");
  Serial.println(Global);
  Serial.print("Local = ");
  Serial.println(Local);
  
  // These work fine:
  CallF(0);
  CallF(1);
  CallF(2);
  
  // These now work too!
  CallF(Local); // Calls FuncB
  CallF(Global); // Calls FuncB
  
  // For good measure so does this:
  for(byte a = 0; a <= 2; a++)
  {
    CallF(a);
  }
}

void loop(){}

void FuncA(){
  Serial.println("Function A");
}

void FuncB(){
  Serial.println("Function B");
}

void FuncC(){
  Serial.println("Function C");
}

And the include file is this:

#include <arduino.h>

typedef void (* myFunction) ();

void FuncA(void);
void FuncB(void);
void FuncC(void);

PROGMEM myFunction Farr[] PROGMEM  = {FuncA, FuncB, FuncC};

If you comment out the lines under 'option A' and uncomment 'option B', it won't compile. This is the problem I'm trying to solve.

Arduino.zip (1.13 KB)

Why the lengthy path to the include? Put the Include.h file in the same folder as the .ino file. Then this compiles:

#define CallF(Num) ((myFunction) pgm_read_word (&Farr [Num])) ()
#include "Include.h"

...

I wanted to avoid that if possible. If it's in the same folder as the rest of the Arduino code, the IDE will open it, ignore changes to it, and save over it. It's a similar problem to the one discussed in the other thread I mentioned.

The best solution there was to use an alternate editor, with only some of the files open. But if there's a way to keep compatibility with the Arduino IDE and compile it in its current location, that would be even better.

Make a library then.

Or edit the .h file in the IDE. What's the big deal with that?