0

I am having a problem implementing a the digitalRead() function in arduino uno.I want digitalRead to return 0 when nothing is connected and return 1 when it is connected to +5 volt.But seems like digitalRead returns random values when it is not connected to anything. I have kind of solved the problem by a small piece of code to stabilize the value i'll attach the code here but if any other solution is avalable..Please help.

The function is as follows:-

bool getValue()

{

String k="";

if(digitalRead(3)==HIGH)

k="HIGH";

else

k="LOW";

bool f=true;

for(int i=0;i<1000;i++)

{
String z;

  if(digitalRead(3)==HIGH)

  z="HIGH";

  else

  z="LOW";


  if(k!=z)

  {

    f=false;

    break;

  }

}


if(f==true)

return true;

else

return false;

}
3

The solution is called a pull down resistor and it's exactly the same as when you are using a button - the button is what connects the pin to +5V. The pull down resistor (usually around 10kΩ) connected to ground is what makes the pin read LOW at other times.

  • 2
    Do you (original poster) really need it to read 0 when disconnected? The Arduinos have a built-in pull-up resistor which you can easily enable (arduino.cc/en/Tutorial/DigitalPins), meaning it will read 1 when disconnected. Your external device then has to pull the line to 0v to signal something. This is a very common way of doing things. – Mark Smith Dec 16 '16 at 12:00
  • Thanks Mark... I'll implement it in that manner..Thanks again – Sparsha Saha Dec 16 '16 at 12:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.