In the following code, I was expecting that the digitalWrite would return the pin to LOW. That is not happening.
"input12" is set to 12. Pine 12 is set as input.
When I Physically set the pin High with voltage (briefly tapping a jumper from +3V to the Pin, the code enters the if statement.
I was expecting the digitalWrite(input12, LOW would set the pin to LOW. Do I have to also physically set the pin to low by touching the jumper to ground?
void loop(){
Pin12State = digitalRead(input12);
Serial.print(Pin12State);
delay(1000);
if (Pin12State == HIGH) {
Serial.print("LED ON ");
delay(3000);
Serial.print("LED OFF ");
digitalWrite(input12, LOW);
}
}
If the pin is already set INPUT, digitalWrite'ing it LOW does nothing - it's not an output.
If the pin is set INPUT_PULLUP, digitalWrite'ing it LOW turns off the pullup (making it INPUT).
Note that a pin set INPUT, and not connected to anything else, may read high or low essentially at random, as it will act like an antenna picking up noise from the environment. You need either a pullup (either INPUT_PULLUP or an external pullup) or pulldown resistor to keep it at a defined value when nothing else is connected. For external pullups/pulldowns, values of 10k or 4.7k are a good default - higher values may be appropriate if the wire run is short and power consumption while the pin; if the wire is long, a stronger pullup, maybe even 1k, might be necessary (longer wires pick up more noise).
Because the AVRs have internal pullups, the normal way to do a button (for example) is to have the pin set INPUT_PULLUP, and connect to ground when pressed, and have your code look for the pin going LOW rather than HIGH when checking if the button is pressed.