Hi,
I've used this as a base to test my setup. http://www.instructables.com/id/Arduino-Button-Tutorial/ this originally worked fine but I've modified it to have 2 buttons and 2 LED's.
The problem I have is that on the first loop 1 LED changes to ON and I can not figure out why. In the setup I initialize them as LOW and the button has not been pressed so it shouldn't change.
Here is my code.
int Buttons[] = { 0, 11, 15};
int LEDs[] = { 0, 9, 7 };
int numofButtons = 2;
int numofLEDs = 2;
int j;
int i;
int k;
int l;
int m;
#define DELAY 50 // Delay per loop in ms
//////////////////////////////////////////////////////////////////////////////
// Setup Buttons
int buttons_now_pressed[] = {};
boolean buttons_was_pressed[] = { false, false, false }; // previous state
boolean events[] = { 0, 1, 2 };
boolean raising_edge[] = {};
int running;
void setup()
{
Serial.begin(9600);
for (j = 1; j < (numofButtons); j++)
{
pinMode(Buttons[j], INPUT);
digitalWrite(Buttons[j], LOW); // push-down
Serial.println("Initialize Button " + j);
}
for (i = 1; i < (numofLEDs); i++)
{
pinMode(LEDs[i], OUTPUT);
digitalWrite(LEDs[i], LOW);
Serial.println("Initialize LEDs " + i);
}
for (k = 1; k < (numofButtons); k++)
{
buttons_was_pressed[k] = false;
Serial.println("Initialize Buttons_was_pressed " + k);
}
}
boolean handle_button()
{
for (l = 1; l < (numofButtons); l++)
{
buttons_now_pressed[l] = !digitalRead(Buttons[l]); // pin low -> pressed
events[l] = buttons_now_pressed[l] && !buttons_was_pressed[l];
buttons_was_pressed[l] = buttons_now_pressed[l];
}
}
void loop()
{
delay(5000);
// handle button
handle_button();
// Serial.println("Start Loop");
for (m = 1;m < (numofButtons); m++)
{
raising_edge[m] = events[m];
Serial.print(raising_edge[m]);
// do other things
Serial.print(raising_edge[m] ? "^" : ".");
if (raising_edge[m] == true)
{
running = digitalRead(LEDs[m]);
running = !running;
Serial.print(" Change LED" + String(m) + " ");
digitalWrite(LEDs[m], running);
}
// add newline sometimes
static int counter = 0;
if ((++counter & 0x3f) == 0)
Serial.println();
delay(DELAY);
}
}