Skip to main content
Added more explanations.
Source Link
Nick Gammon
  • 38.9k
  • 13
  • 70
  • 126

yeah but i want to be able to store the function in an array with the set parameters

Do you? I wonder why.

Anyway, you can do that by making an array of lambda functions like this:

const int COUNT = 100;

int playNote(int midi, int row, int col, int len, bool short_led = false);

void (*SongSeq[COUNT])() = 
 {
 [] { playNote(0x40, 3, 1, 414); } ,
 [] { playNote(0x3e, 2, 4, 414); } ,
 [] { playNote(0x3c, 2, 2, 414); } ,
 [] { playNote(0x3e, 2, 4, 414); } ,

 // ... and so on 

 };

void setup() 
  {
  Serial.begin (115200);
  }

void loop() 
  {
  for (int i = 0; i < COUNT; i++)
    {
    if (SongSeq [i])
      SongSeq [i] ();
    }
  }

int playNote(int midi, int row, int col, int len, bool short_led)
{
  Serial.print ("Playing note ");
  Serial.println (midi);
  delay (100);
}

yeah but i want to be able to store the function in an array with the set parameters

Do you? I wonder why.

Anyway, you can do that by making an array of lambda functions like this:

const int COUNT = 100;

int playNote(int midi, int row, int col, int len, bool short_led = false);

void (*SongSeq[COUNT])() = 
 {
 [] { playNote(0x40, 3, 1, 414); } ,
 [] { playNote(0x3e, 2, 4, 414); } ,
 [] { playNote(0x3c, 2, 2, 414); } ,
 [] { playNote(0x3e, 2, 4, 414); } ,

 // ... and so on 

 };

void setup() 
  {
  Serial.begin (115200);
  }

void loop() 
  {
  for (int i = 0; i < COUNT; i++)
    {
    if (SongSeq [i])
      SongSeq [i] ();
    }
  }

int playNote(int midi, int row, int col, int len, bool short_led)
{
  Serial.print ("Playing note ");
  Serial.println (midi);
  delay (100);
}
Source Link
Nick Gammon
  • 38.9k
  • 13
  • 70
  • 126

What you have done will certainly call the function. Since it is always the same function, just store the arguments into an array. Something like this:

const int COUNT = 100;

struct 
  {
  int midi;
  int row;
  int col; int len;
  bool short_led;
  } notes [COUNT] = {
  { 0x40, 3, 1, 414 },  //Quarter note: E
  { 0x3e, 2, 4, 414 },  //Quarter note: D
  { 0x3c, 2, 2, 414 },  //Quarter note: C

  // and so on
  };

int playNote(int midi, int row, int col, int len, bool short_led = false);

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

void loop() 
  {
  for (int i = 0; i < COUNT; i++)
    {
    if (notes [i].midi)
      playNote (notes [i].midi, notes [i].row, notes [i].col, 
                notes [i].len, notes [i].short_led);
    }
  }

int playNote(int midi, int row, int col, int len, bool short_led)
{
    int len1, len2;
    if (short_led) {
        len1 = len * 3 / 4;
        len2 = len * 1 / 4;
    } else {
        len1 = len;
        len2 = 0;
    }
    noteOn(0x90, midi, 100);
    digitalWrite(LedR[row], HIGH);
    digitalWrite(LedC[col], LOW);
    delay(len1);
    digitalWrite(LedR[row], LOW);
    digitalWrite(LedC[col], HIGH);
    delay(len2);
    noteOff(0x90, midi, 0);
}