Boolean AND question

Hi, im trying to be able to turn a led (for example) if two buttons are pressed for like 3sec, im using this code

if(digitalRead(5) == HIGH && digitalRead(4) == HIGH) { ini4 = millis();}
   if ((millis() - ini4) > 3000) {
       digitalWrite(13,HIGH);
   }

where ini4 is a "long" variable.

but its triggerings if I press button 1 or 2.

Any idea what may be causing the problem? Thanks

What is the initial value of "ini4" ?

BTW, consistent indentation would be helpful.

dansku, your indentation can be misleading. Let's reformat:

if(digitalRead(5) == HIGH && digitalRead(4) == HIGH)
{
    ini4 = millis();
}

if ((millis() - ini4) > 3000) {
    digitalWrite(13,HIGH);
}

One of your problems lies in that you are testing for the 3-second
timeout regardless of the condition of the switches!

Also, you need to account for 'switch bounce'. This will make the digital
inputs vary between HIGH and LOW for, oh... about 100 to 200-milliseconds
after the switches are physically pressed. This time can be longer if the
switch contacts are dirty. See Switch - Wikipedia

Depending on how quickly you run this section of code and testing the
two buttons your program is likely to catch a "bounce" of the switch and
read a LOW even though you've got a concrete block sitting on the
switch holding it down. :slight_smile:

You might try something like this:

ini4 = millis();
while ((digitalRead(5) == HIGH) && (digitalRead(4) == HIGH))
{
    delay(200);       // wait for switches to stop bouncing
    if ((millis() - ini4) > 3000) {
        digitalWrite(13, HIGH);
    }
}
// when either button is released, turn off the LED.
digitalWrite(13, LOW);

Two downsides with this code is that pin 13 will get written with HIGH
every 200-milliseconds once the two buttons are pressed. A LOW will
be written to pin 13 everytime this code segment is executed when
both buttons are not pushed. But... this shouldn't be a big issue.

This code segment will also need to be modified if you want the Arduino
to do other processing while the switches are pressed together.

Hope this helps some....