create a function to initialyze more than 32 buttons

hi everybody,

I’m working on a project where i have a lots of button.

so i create my own variable like this one:

//Buttons-----------------------------------------

typedef struct Button Button;

struct Button

{

boolean curState;//1 is ON, 0 is OFF

boolean prevState;

boolean pressed;

boolean justPressed;

boolean justRelease;

boolean hold;// 1 is holding

byte counter;//count number of push on the button

unsigned long curTime;

};

the thing is that i have to initialise more than 32 buttons.

How can i create a function to simplify this code?

//backward button-------------------------------

backBtn.justRelease = 0;

backBtn.justPressed = 0;

backBtn.curState = ((secondByte & BTN_BACK) ? 1:0);

if (backBtn.curState != backBtn.prevState){

if (backBtn.pressed == LOW && backBtn.curState == HIGH) backBtn.justPressed = HIGH;

if (backBtn.pressed == HIGH && backBtn.curState == LOW) backBtn.justRelease = HIGH;

backBtn.pressed = backBtn.curState;

}

backBtn.prevState = backBtn.curState;

//forward button-------------------------------

fwdBtn.justRelease = 0;

fwdBtn.justPressed = 0;

fwdBtn.curState = ((secondByte & BTN_FWD) ? 1:0);

if (fwdBtn.curState != fwdBtn.prevState){

if (fwdBtn.pressed == LOW && fwdBtn.curState == HIGH) fwdBtn.justPressed = HIGH;

if (fwdBtn.pressed == HIGH && fwdBtn.curState == LOW) fwdBtn.justRelease = HIGH;

fwdBtn.pressed = fwdBtn.curState;

}

fwdBtn.prevState = fwdBtn.curState;

and more…

thank you for your help :wink:

Learn some basics of C++ and make a button class with initialization in the constructor. Then instantiate 32 objects of that class.

This would work provided you use it on a microcontroller with enough memory:

#include <Automaton.h>
#include <Atm_button.h>

Att_button button[32];
TinyFactory factory;

void btn_change( int press, int idx ) 
{
  if ( press ) {

  }
}

void setup() 
{
  for ( int i = 0; i < 32; i++ ) {
    button[i].begin( i ).onPress( btn_change, i );
    factory.add( button[i] );    
  }
}

void loop() 
{
  factory.cycle();
}

It would be more memory efficient to wite a state machine that handles all 32 buttons in one instance.

Automaton framework can be found here: https://github.com/tinkerspy/Automaton/wiki