Digital Inputs and Outputs with Arduino

Often the main purpose of a project is to detect, and interact with the world around it, and to do this we need to leverage the Input and Output pins of the board.

Initially we will cover the Digital IO on the board, as this is a simple ON / OFF state Input or Output.

 

Note Icon Note:

Check your specific board model for pin locations, voltages and tolerances when adding external hardware.

 

Pin Mode

To use a Digital Pin we first have to configure it in our software, using the pinMode() function, and supplying the pin we want to configure, and whether it is an Input or an Output.

Initially we will set our LED_BUILTIN pin to be an OUTPUT, so we can control the onboard LED.

 

Digital Write

Now we have an output, we will need to set the state of this in our code, to turn the LED On or Off.  This can be done using digitalWrite(), and supplying the pin, and the state HIGH or LOW.

HIGH (1) is where the board will supply power to the pin (3.3v or 5v depending on hardware)

LOW (0) is where the board will not supply any power to the pin

Note Icon Note:

The digital IO pins on most boards can only handle very small current draw, so you can directly drive a small LED, but you cannot drive a motor directly from the pin without damaging your board permanently.

 

If we upload the Blink Example to our board we will see the LED flash every second.  We could combine this with our Serial Code and make it so we can turn the LED on and off on demand, using the Serial Monitor.

 

Digital Read

If reading a digitial pins state in your sketch, you will need to first set it as an input using pinMode()

Then we can read the state of the pin using digitalRead(), which will return either a 1 or a 0 depending on the voltage supplied to the pin.

 

If we upload a simple sketch reading the digital pins state, and then outputting that state to the Serial Monitor every 1/10th of a second, we would expect it to just read 0.... but instead it constantly fluctuates between 1 and 0.

As it is not connected, it is left "floating" and to avoid this, we need to add a pull up or pull down resistor, to ensure our pin is set to high, or low when there is no other source of high/low input, but not override it.  This can be done with an external resistor, however a number of boards come with these built in.

To use the internal resistors, simply change the INPUT option in pinMode() to be INPUT_PULLUP or INPUTPULLDOWN, depending on what is available on your board.

 

More detailed information about the above concepts can be found in the Arduino Documentation