Go Down

Topic: How to read a "button"? (Read 461 times) previous topic - next topic

I need close the circuit touching two wires, so, I take to print what was read, via Serial.println(), the problem is, it's reading wrong (prints 1 and 0 in different positions), I don't know what do, check the images. After I touch both wires, so it shows only 0. Below there is the code:

Code: [Select]
int pedal = 6;
int led = 13;
int pedalInput = 0;

void setup() {
  Serial.begin(9600);
  pinMode(pedal, INPUT);
  pinMode(led, OUTPUT);
}

void loop() { 
 
  pedalInput = digitalRead(pedal);

  if(pedalInput == HIGH) {
    Serial.println("1");
    digitalWrite(led, HIGH);
  } else {
    Serial.println("0");
    digitalWrite(led, LOW);
  }
}


What can I do to fix this problem?

Thanks so much!!!

groundfungus

#1
Dec 20, 2013, 01:26 am Last Edit: Dec 20, 2013, 01:29 am by groundfungus Reason: 1
With the two wires not touching you have a "floating input".  The input is very high impedance so will pick up noise.  When you touch the wires the input is pulled to ground.  Change  the line "pinMode(pedal, INPUT); to pinMode(pedal, INPUT_PULLUP);
Now when the wires are not touching the input is held high by the internal pullup resistor and will read 1,  Touch the wires for 0.

Know it's saying that  'INPUT_PULLUP' was not declared in this scope

groundfungus

What version of the IDE are you using?  Go back to pinMode(pedal, INPUT); and add digitalWrite(pedal. HIGH): after.  That is how to enable internal pullups for an older version of the IDE.

Wow man, it's working, thanks!!! I am using an older version.

Go Up