I wrote a small library which could be used to toggle a light with one or more push buttons. It is like the OneButton Library, but with the additional feature, that you can specify more than one button for a specific light.
I am using an int array which contains the pins where the buttons are connected to:
In the header file I do define the array:
private:
int _switchPins[5]; // pins for the light switch(es)
In the cpp I do initialize the array in the constructor:
LightOne::LightOne(int switchPin, int lightPin, boolean activeLow)
{
pinMode(switchPin, INPUT); // sets the switchPin to act as input
pinMode(lightPin, OUTPUT); // set the lightPin to act as output
_switchPins[0] = switchPin;
_switchPins[1] = -1;
_switchPins[2] = -1;
_switchPins[3] = -1;
_switchPins[4] = -1;
Another method could be used to add additional swich pins:
void LightOne::addSwitchPin(int switchPin)
{
for (int i=0; i<5; i++) {
if (_switchPins[i] == -1) {
_switchPins[i] = switchPin;
pinMode(switchPin, INPUT);
if (_activeLow) {
digitalWrite(switchPin, HIGH); // turn on pulldown resistor
}
break;
}
}
} // addSwitchPin
And in the method which gets called from the mail program (kind of loop method of the library), I do check if one of the buttons are pressed:
void LightOne::tick(void)
{
// Detect the input information
int buttonLevel = _buttonReleased;
// look at each configured button if one is pressed (=_buttonPressed)
for (int i=0; i<5; i++) {
if (_switchPins[i] != -1) {
if (digitalRead(_switchPins[i]) == _buttonPressed) {
buttonLevel = _buttonPressed;
}
if (_debug && buttonLevel == _buttonPressed) {
Serial.print("Light-Button PIN ");
Serial.print(_switchPins[i]);
Serial.println(" pressed");
}
}
}
....
In the main Program I am using that library:
#include <LightOne.h>
LightOne light1(4, 13, false);
void setup() {
light1.addSwitchPin(5);
light1.addSwitchPin(6);
}
void loop() {
light1.tick();
}
I am using the Arduino Nano and after the 3rd or 4th Button press I am getting on the Serial Monitor very strange outputs:
Light-Button PIN 5013 pressed
Light-Button PIN -235 pressed
and that not just once, but very very often.
What could go wrong that my int array get messed up?
Thanks
p.s. I do have a much better Java knowledge than C/C++, so I am kind of a newby to C/C++!