Pages: [1]   Go Down
Author Topic: Boolean AND question  (Read 397 times)
0 Members and 1 Guest are viewing this topic.
0
Offline Offline
Jr. Member
**
Karma: 0
Posts: 77
Arduino rocks
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

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

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
Logged

Global Moderator
UK
Offline Offline
Brattain Member
*****
Karma: 290
Posts: 25813
I don't think you connected the grounds, Dave.
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

What is the initial value of "ini4" ?

BTW, consistent indentation would be helpful.
Logged

"Pete, it's a fool looks for logic in the chambers of the human heart." Ulysses Everett McGill.
Do not send technical questions via personal messaging - they will be ignored.

Van Alstyne, TX
Offline Offline
Full Member
***
Karma: 1
Posts: 154
Haven't smoked an Arduino... yet.
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

dansku, your indentation can be misleading.   Let's reformat:
Code:
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 http://en.wikipedia.org/wiki/Switch#Contact_bounce

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. :-)

You might try something like this:
Code:
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....
Logged

Pages: [1]   Go Up
Jump to: