How can i code a button outside a matrix sketch?

Hello, i'm trying to create a button box but want to remove one or 2 of those buttons and give them their seperate inputs/pins. I'm using this sketch i found on a tutorial: ButtonboxSketch - Pastebin.com

How can i program 2 seperate buttons into this sketch?
Thanks.

Please post your sketch here using code tags to make it easy to read and copy for examination as described in How to get the best out of this forum

#include <Keypad.h>
#include <Joystick.h>

//DEFINITIONS
#define ENABLE_PULLUPS
#define NUMROTARIES 2 //replace "?" with number of rotary encoders you are using
#define NUMBUTTONS 18 //replace "?"with number of buttong you are using
#define NUMROWS 6 //replace "?" with number of rows you have
#define NUMCOLS 4 //replace "?" with number of columns you have

//BUTTON MATRIX
//first change number of rows and columns to match your button matrix, 
//then replace all "?" with numbers (starting from 0)
byte buttons[NUMROWS][NUMCOLS] = {
  {0,1,2,3},
  {4,5,6,7},
  {8,9,10,11},
  {12,13,14,15},
  {16,17,18,19},  
  {20,21,22,24}
  
 
 
};

struct rotariesdef {
  byte pin1;
  byte pin2;
  int ccwchar;
  int cwchar;
  volatile unsigned char state;
};

//ROTARY ENCODERS
//each line controls a different rotary encoder
//the first two numbers refer to the pins the encoder is connected to 
//the second two are the buttons each click of the encoder wil press 
//do NOT exceed 31 for the final button number
rotariesdef rotaries[NUMROTARIES] {
  {0,1,22,23,0}, //rotary 1
  {2,3,24,25,0} //rotary 2


};

#define DIR_CCW 0x10
#define DIR_CW 0x20
#define R_START 0x0

#ifdef HALF_STEP
#define R_CCW_BEGIN 0x1
#define R_CW_BEGIN 0x2
#define R_START_M 0x3
#define R_CW_BEGIN_M 0x4
#define R_CCW_BEGIN_M 0x5
const unsigned char ttable[6][4] = {
  // R_START (00)
  {R_START_M,            R_CW_BEGIN,     R_CCW_BEGIN,  R_START},
  // R_CCW_BEGIN
  {R_START_M | DIR_CCW, R_START,        R_CCW_BEGIN,  R_START},
  // R_CW_BEGIN
  {R_START_M | DIR_CW,  R_CW_BEGIN,     R_START,      R_START},
  // R_START_M (11)
  {R_START_M,            R_CCW_BEGIN_M,  R_CW_BEGIN_M, R_START},
  // R_CW_BEGIN_M
  {R_START_M,            R_START_M,      R_CW_BEGIN_M, R_START | DIR_CW},
  // R_CCW_BEGIN_M
  {R_START_M,            R_CCW_BEGIN_M,  R_START_M,    R_START | DIR_CCW},
};
#else
#define R_CW_FINAL 0x1
#define R_CW_BEGIN 0x2
#define R_CW_NEXT 0x3
#define R_CCW_BEGIN 0x4
#define R_CCW_FINAL 0x5
#define R_CCW_NEXT 0x6

const unsigned char ttable[7][4] = {
  // R_START
  {R_START,    R_CW_BEGIN,  R_CCW_BEGIN, R_START},
  // R_CW_FINAL
  {R_CW_NEXT,  R_START,     R_CW_FINAL,  R_START | DIR_CW},
  // R_CW_BEGIN
  {R_CW_NEXT,  R_CW_BEGIN,  R_START,     R_START},
  // R_CW_NEXT
  {R_CW_NEXT,  R_CW_BEGIN,  R_CW_FINAL,  R_START},
  // R_CCW_BEGIN
  {R_CCW_NEXT, R_START,     R_CCW_BEGIN, R_START},
  // R_CCW_FINAL
  {R_CCW_NEXT, R_CCW_FINAL, R_START,     R_START | DIR_CCW},
  // R_CCW_NEXT
  {R_CCW_NEXT, R_CCW_FINAL, R_CCW_BEGIN, R_START},
};
#endif

//BUTTON MATRIX PART 2
byte rowPins[NUMROWS] = {4,5,6,7,8,9}; //change "?" to the pins the rows of your button matrix are connected to
byte colPins[NUMCOLS] = {10,14,15,16}; //change "?" to the pins the rows of your button matrix are connected to

Keypad buttbx = Keypad( makeKeymap(buttons), rowPins, colPins, NUMROWS, NUMCOLS);

//JOYSTICK SETTINGS
Joystick_ Joystick(JOYSTICK_DEFAULT_REPORT_ID,
  JOYSTICK_TYPE_JOYSTICK,
  32, //number of buttons
  0, //number of hat switches
  //Set as many axis to "true" as you have potentiometers for
  false, // y axis
  false, // x axis
  true, // z axis
  true, // rx axis
  false, // ry axis
  false, // rz axis
  false, // rudder
  false, // throttle
  false, // accelerator
  false, // brake
  false); // steering wheel

const int numReadings = 20;
 
int readings[numReadings];      // the readings from the analog input
int index = 0;              // the index of the current reading
int total = 0;                  // the running total
int currentOutputLevel = 0;

//POTENTIOMETERS PART 1
//add all the axis' which are enabled above
int zAxis_ = 0;
int RxAxis_ = 0;   

               
//POTENTIOMETERS  PART 2
//Which pins are your potentiometers connected to?
int potentiometerPin1 = A0; //Change "?" to the pin your potentiometer is connected to
int potentiometerPin2 = A1;
const bool initAutoSendState = true;


void setup() {
  Joystick.begin();
  rotary_init();
  for (int thisReading = 0; thisReading < numReadings; thisReading++) {
    readings[thisReading] = 0;
  }
}

void loop() {

  CheckAllEncoders();
  CheckAllButtons();
  CheckAllPotentiometers();
 
}

//POTENTIOMETERS PART 3
//change the details to match teh details above for each potentiometer you are using
void CheckAllPotentiometers(){
                           
  //potentiometer 1
  currentOutputLevel = getAverageOutput(potentiometerPin1);
  zAxis_ = map(currentOutputLevel,0,1023,0,255);
  Joystick.setZAxis(zAxis_); 

  //potentiometer 2
  currentOutputLevel = getAverageOutput(potentiometerPin2);
  RxAxis_ = map(currentOutputLevel,0,1023,0,255);
  Joystick.setRxAxis(RxAxis_);


}

int getAverageOutput(int pinToRead){
  index = 0;
  total = 0; 
 
  while (index < numReadings){
    readings[index] = analogRead(pinToRead);
    total = total + readings[index];
    index = index + 1;
    //delay (1);
  }
  return total / numReadings;
}


void CheckAllButtons(void) {
      if (buttbx.getKeys())
    {
       for (int i=0; i<LIST_MAX; i++)   
        {
           if ( buttbx.key[i].stateChanged )   
            {
            switch (buttbx.key[i].kstate) { 
                    case PRESSED:
                    case HOLD:
                              Joystick.setButton(buttbx.key[i].kchar, 1);
                              break;
                    case RELEASED:
                    case IDLE:
                              Joystick.setButton(buttbx.key[i].kchar, 0);
                              break;
            }
           }   
         }
     }
}


void rotary_init() {
  for (int i=0;i<NUMROTARIES;i++) {
    pinMode(rotaries[i].pin1, INPUT);
    pinMode(rotaries[i].pin2, INPUT);
    #ifdef ENABLE_PULLUPS
      digitalWrite(rotaries[i].pin1, HIGH);
      digitalWrite(rotaries[i].pin2, HIGH);
    #endif
  }
}


unsigned char rotary_process(int _i) {
  //Serial.print("Processing rotary: ");
  //Serial.println(_i);
  unsigned char pinstate = (digitalRead(rotaries[_i].pin2) << 1) | digitalRead(rotaries[_i].pin1);
  rotaries[_i].state = ttable[rotaries[_i].state & 0xf][pinstate];
  return (rotaries[_i].state & 0x30);
}

void CheckAllEncoders(void) {
  Serial.println("Checking rotaries");
  for (int i=0;i<NUMROTARIES;i++) {
    unsigned char result = rotary_process(i);
    if (result == DIR_CCW) {
      Serial.print("Rotary ");
      Serial.print(i);
      Serial.println(" <<< Going CCW");
      Joystick.setButton(rotaries[i].ccwchar, 1); delay(50); Joystick.setButton(rotaries[i].ccwchar, 0);
    };
    if (result == DIR_CW) {
      Serial.print("Rotary ");
      Serial.print(i);
      Serial.println(" >>> Going CW");
      Joystick.setButton(rotaries[i].cwchar, 1); delay(50); Joystick.setButton(rotaries[i].cwchar, 0);
    };
  }
  Serial.println("Done checking");
}

So i want to have seperate buttons that use 1 single pin. Sort of like how the rotaries are coded now. Each pin controls each button. Looking at the example sketch that is included in the JoystickLibrary 2.0

// Simple example application that shows how to read four Arduino
// digital pins and map them to the USB Joystick library.
//
// Ground digital pins 9, 10, 11, and 12 to press the joystick 
// buttons 0, 1, 2, and 3.
//
// NOTE: This sketch file is for use with Arduino Leonardo and
//       Arduino Micro only.
//
// by Matthew Heironimus
// 2015-11-20
//--------------------------------------------------------------------

#include <Joystick.h>

Joystick_ Joystick;

void setup() {
  // Initialize Button Pins
  pinMode(9, INPUT_PULLUP);
  pinMode(10, INPUT_PULLUP);
  pinMode(11, INPUT_PULLUP);
  pinMode(12, INPUT_PULLUP);

  // Initialize Joystick Library
  Joystick.begin();
}

// Constant that maps the phyical pin to the joystick button.
const int pinToButtonMap = 9;

// Last state of the button
int lastButtonState[4] = {0,0,0,0};

void loop() {

  // Read pin values
  for (int index = 0; index < 4; index++)
  {
    int currentButtonState = !digitalRead(index + pinToButtonMap);
    if (currentButtonState != lastButtonState[index])
    {
      Joystick.setButton(index, currentButtonState);
      lastButtonState[index] = currentButtonState;
    }
  }

  delay(50);
}

I tried putting this code in the existing sketch but then i run in the issue of mapping the button to act as the right buttonpress, which has to be 26 in this case as button 22-25 are the rotaries and the first 21 from the matrix.
this code also has it's own index which already is in the sketch.
Any help is greatly appreciated!!!

Hi marmitaa,

to really help you we (the other users in this forum) need some additional information.

The most important thing is a hand-drawn schematic that shows

  • how many buttons
  • connected to which IO-pins
    don't use a fritzing-picture! I repeat don't use a fritzing-picture!
    a picture of a hand-drawn schematic with pencil & paper is much more liked in the forum and absolutely sufficient.

Some additional information: a button-matrix is wired with a small number of IO-pins and a special kind of "scanning" is done to detect a buttonpress.

If you would press two buttons at the same time in a button-matrix this can result in strange results (depending on which buttons you press) due to the nature of the wiring and the scanning.

So if you would give an overview about your project and the functions of all buttons much better suiting suggestions can be made.
It might even be that another solution than buttons is better to achieve what you want.

best regards Stefan

Thank you for the reply. I hope this image will suffice but i will add a handdrawn schematic as requested.
The power button and toggle switch both use LED's. I want these 2 to be outside of the matrix as the LED's don't work properly inside a matrix. Therefore i need to code 2 seperate buttons for 2 seperate pins, in my case the only 2 pins not assigned or connected to anything is A2 and A3. Now if understand correctly the "Keypad Library" is used for the matrix and "Joystick Library" for the rotary encoders and potentiometers. The rotary encoders are outside the matrix except for the pushbutton of the rotary's, those are wired to the matrix aswell. Disregard the matrix row and column connected to the LED switch and LED Power button shown on the schematic, as i obviously need them to be connected to a single pin, A2 and A3 respectively.

Number of buttons inside the matrix: 16 (including 2 pushbuttons of the rotary's)
Number of buttons outside the matrix: 4 buttons for 2 rotary encoders and i obviously want the LED button and switch to be outside the matrix aswell coming on 6 buttons

So 22 buttons in total.

Number of potentiometers: 2

As i said earlier the rotary's left and right turn are coded to act as button presses 22 and 23. I need to achieve something similar to that, that i can code it like the rotary's to act as the button presses i assign the button/switch to. In my case button press number 26 and 27 since those are the last spots available. The first 21 buttons are indexed(?) to the matrix buttons, number 22 to 25 are the 2 rotary's and 26 and 27 i need to be the switch and button. That is what i can't seem to figure out.

The picture with the additional lines show how things are wired together.
But still in a hard to follow way.
Can you please transfer your schematic to look like this one?
grafik

This is the standard way how a matrix-wiring is drawn:
vertical colums und horizontal rows
Take more space between each button and then give each button a very easy to identify signature.
This signature must be very very very unique to completely eliminate the risk of confusion.

not precise enough description: Which is the power-button?? Which is the toggle-switch???
Just another question that shows that unique and unmistakable signatures for each button are nescessary and must be documented.

What does "both use LEDs" mean?
You put both in series with the switch?
A LED should switch on if the switch is closed?
Should the LED switch on beeing physically wired to the switch?
Should the LED switch on through an extra IO-pin?

From all these questions you can see that a much more detailed description is nescessary to help you.

best regards Stefan

Hello Stefan, i thank you very much for your time.
Sorry for the bad schematic, i hope this will clarify some things up regarding the wiring. I know it still is pretty hard to understand. I put the image of the buttonbox above 6 empty matrix spots (right of the 6 toggle switches) and 2 red crosses where the potentiometers are located, as they are not included in the matrix. So the red crosses represent empty matrix spots aswell.

The blue and red numbers are supposed to represent that those are not included in the matrix.

The power button has a "power symbol" which is why i refer to it that way. It functions just like a normal button it just had a built in LED. Same goes for the LED Switch on the right of the "power button", it functions just like the 6 other switches but has a built in LED. Which is also why i can't include them in the matrix.

What does "both use LEDs" mean?

Both have a built in LED.

A LED should switch on if the switch is closed?

Yes, the LED should only go on when pressed/switched.

Should the LED switch on being physically wired to the switch?

The LED switch should only be connected to a single pin.

Should the LED switch on through an extra IO-pin?

No, either be supplied by the single IO pin's 5v or use the VCC pin. Preferably only use a single pin.

Thank you very much for the help!
Kind regards,
Ilias.

The reason why I would prefer something like a number or a single letter for each switch is that is much easier to "quote" a switch. Just type the number of letter on the keyboard.
Now to make 100% sure which switch I mean I have to cut and paste a part of your picture

The two buttons in the picture above seem to have three "connectors" named
"GND"
"Vcc"
and an IO-Pin-number A2 / A3

Does this mean when-ever you press or flip the switch into "ON"-position the LED lights up automatically because there is some internal wiring in the switch?

And the IO-pin A2/A3 is for detecting the switches/buttons state?

Did you test if the LED lights up automatically?
Is the voltage simply 5V? Which would be unusal. In industry the standard-voltage is 10V or 24V

best regards Stefan

I hope this isn't too confusing. This is essentially how the buttons are mapped.

Yes, i believe so. The switch has just 3 terminals, 1 for ground 1 for voltage and 1 for input. The button has 5 terminals as shown by this schematic and picture. The 5 terminal can work in the matrix because the led pins are seperate but unfortunately it doesn't work with the switch.

Yes, that's right. And map/set/assign/index the particular button and switch to the right number, in this case 26 and 27 since the first 25 buttons and switches are already from the matrix and rotary encoders. Which is also why i posted the "JoystickButton" example code. The issue i presume to be how i could possibly manually index them just like how the rotary encoders are manually set:

//ROTARY ENCODERS //each line controls a different rotary encoder //the first two numbers refer to the pins the encoder is connected to //the second two are the buttons each click of the encoder wil press //do NOT exceed 31 for the final button number rotariesdef rotaries[NUMROTARIES] { {0,1,22,23,0}, //rotary 1 {2,3,24,25,0} //rotary 2

Yes, i know it's uncommon but the button is 5V, the switch however is 12V i calculated the resistor needs to be 330 for that switch at 5V. I did test them on a breadboard and it worked fine with the resistor.

Thank you so much Stefan.

You are still not precise enough (at least for me)
What is still nclear to me
There is a schematic not hand-drawn (like to told you) but using computer-graphics
that don't suit to the real hardware

Your computergraphic shows a part "device" instead of what it really is. What is "device"?
The LED?
Your button-matrix?

Then you write about the "button" what is so hard about giving each button a number and always quote that number ???

We are again on the level of assumings instead of beeing sure.
The things you have detailed have 3 terminals. Now you are writing about 5 terminals
Which button do you mean? a green one?

Why don't you show how your 5 terminal-button is wired?

marmita: if you are not able to provide precise defined information I'm out!

I literally gave you everything you asked for, and you still have the audacity to say that it ain't clear enough? How clear do you want it to be? You even asked what button the LED is and what switch the LED is, while there is literally and clearly only 1 LED button and 1 LED switch. You keep disregarding the real issue which is withing the code. How the wiring is setup is completely irrelevant to begin with, the only thing it does is show what i want to achieve considering the how the rotary's are coded.

By all means, leave. please.

left