Go Down

Topic: Code for button press detection (Read 475 times) previous topic - next topic

harshvardhan

Jan 21, 2013, 05:16 pm Last Edit: Jan 21, 2013, 05:53 pm by harshvardhan Reason: 1
is this code allright?

Code: [Select]
int  button()

  int y=digitalRead(8);
  if(y==HIGH)
  {             
    y=LOW ;
    delay(1000);

    y=digitalRead(8);
    if(y==LOW)
      return 1;
    else                   
      return 2 ;     
  }   

  else return 0;


}

it doesnt seem to work  :/  
it should return 2 if its a long press
1 if it is a short press
and 0 if it doesnt detect  any button

abrookfield

Normally, button presses go from HIGH to LOW (switch contact to gnd) - Looks like you're running LOW to HIGH

www.reeftopper.com

Arrch

Start by fixing your indentation: Put each curly brace on its own line and use the Tools > Auto Format function in the Arduino IDE. Then, manually copy and paste the code from the IDE to the forums (don't use the Copy to Forum function) surrounding it with CODE tags.

UKHeliBob

In what way does it not work ?
Have you tried putting some Serial.prints in there to see what the value of y is at various points ?
Please do not send me PMs asking for help.  Post in the forum then everyone will benefit from seeing the questions and answers.

harshvardhan

yea, it returns erratic value
when i put my hand close to the wire, it returns different values



Code: [Select]
int  button()

  int y=digitalRead(8);
  if(y==HIGH)
  {             
    y=LOW ;
    delay(1000);

    y=digitalRead(8);
    if(y==LOW)
      return 1;
    else                   
      return 2 ;     
  }   

  else return 0;


}

harshvardhan


Normally, button presses go from HIGH to LOW (switch contact to gnd) - Looks like you're running LOW to HIGH




could u please ellaborate on that
and yes, my switch normally passes no current (atleast thats how i planned it to be), if i press, the circuit is completed

Arrch

#6
Jan 21, 2013, 05:54 pm Last Edit: Jan 21, 2013, 05:56 pm by Arrch Reason: 1
Your input pin is floating then. You need to enable the internal pull-up resistor so that when the switch is open, the input will read HIGH. You also need to modify your circuit so that pressing the button will connect the input pin to GND.

PaulS

What is connected to pin 8? A complete diagram, please.

What you have sounds a lot like a floating pin condition, caused by not using proper pullup or pulldown resistors.

Go Up