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;
}
1 Answer 1
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.
-
2Do 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– Mark Smith2016年12月16日 12:00:51 +00:00Commented Dec 16, 2016 at 12:00
-
Thanks Mark... I'll implement it in that manner..Thanks againSparsha Saha– Sparsha Saha2016年12月16日 12:52:31 +00:00Commented Dec 16, 2016 at 12:52