A
A
Alexander Movchan2015-06-19 15:43:30
Arduino
Alexander Movchan, 2015-06-19 15:43:30

Why does digitalRead randomly return HIGH?

I wrote the first program on arduino (mega 2560): close the wires - the LED is on, open it - it does not light.

int ledPin = 13;
int switchPin = 10;


void setup()
{
  pinMode(switchPin, INPUT);
  pinMode(ledPin, OUTPUT);
}

void loop()
{
  digitalWrite(ledPin, digitalRead(switchPin));
  delay(250);
}

So, when I close it, everything is fine - it glows, but when I open it, the LED starts blinking.
Why does digitalRead sometimes return true when there is actually no signal?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Gusev, 2015-06-19
@Alexander1705

Use pull-down/pull-up resistors to avoid picking up interference.
pulling:
Pressing: Vout = Vcc
No pressing: Vout = 0
pulling:
Pressing: Vout = 0
No pressing: Vout = Vcc

A
Alexander Komarchuk, 2015-06-19
@AlexanderKomarchouk

In Atmega, the port is very sensitive, and accepts noise on the line as a change in the logic signal at the input.
To avoid this, you can connect a resistor, for example, 10 kOhm, between the input and + power supply, i.e. "pull up to power", or use the programmable "pull-up" resistors "built-in" in the microcontroller.
For this you need to write:

void setup()
{
  pinMode(switchPin, INPUT_PULLUP);
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question