Hi
I am trying to understand how to call functions correctly
I am using an example from this forum that uses a button latch to turn on and off an LED.
Putting this code into a function and then calling it works fine
I now have 4 buttons and 4 LEDs
I want to press one of the 4 buttons and the corresponding LED lights up. push it again and the LED turns off.
My code only works if all the buttons are pressed at once, not one at a time. Any suggestions on how I go about it?
my code:
uint32_t start, dbStart;
const byte btn1 = 2, btn2 = 3, btn3 = 4, btn4 = 5, led1 = 17, led2 = 16, led3 = 15, led4 = 14, dbTime = 15;
int btn = 0;
int led = 0;
bool pinState = true,
btnState = true,
prevBtnState = true,
latch = false;
void setup() {
Serial.begin(9600);
Serial.println("ready:");
pinMode(btn1, INPUT);
pinMode(led1, OUTPUT);
pinMode(btn2, INPUT);
pinMode(led2, OUTPUT);
pinMode(btn3, INPUT);
pinMode(led3, OUTPUT);
pinMode(btn4, INPUT);
pinMode(led4, OUTPUT);
}
void loop() {
button(btn1, led1); // better? method of calling the function
button(btn2, led2);
button(btn3, led3);
button(btn4, led4);
//btn = btn1; led = led1; button(); // works if its the only line
//btn = btn2; led = led2; button(); // if these thre lines
//btn = btn3; led = led3; button(); // are included,
//btn = btn4; led = led4; button(); // then all buttons need to be pressed at once
}
void button(int btn, int led) {
// debounce button ++++++++++++++++
if (digitalRead(btn) != pinState) // get state of pin 2
{
dbStart = millis(); // reset db timer
pinState = !pinState; // now they are equal, won't enter
} // here again unless pin state changes
if (millis() - dbStart > dbTime) // db timer has elapsed
btnState = pinState; // button state is valid
//+++++++++++++++++++++++++++++++++++
if (btnState != prevBtnState && btnState == HIGH) // btnState changed
{
// if button pressed and NOT latched
if (!latch)
{
latch = true; // prevents entry while latched
digitalWrite(led, HIGH);
}
else
{
// if button pressed while latched,
latch = false;
digitalWrite(led, LOW);
}
Serial.print( "LED is ");
if (latch)
{
Serial.println("ON");
}
else
{
Serial.println("OFF");
}
}
prevBtnState = btnState;
}
Extra Question: I don't understand the significance of using the following line to label the dbStart integer
uint32_t start, dbStart;
instead of the more usual
unsigned long dbStart= 0;