Source Code. Projects. Nerd Stuff. Art Stuff.

Digital I/O

Digital vs Analog

In many cases, you only need to know one thing about the physical world: whether something is true or false. In these cases, you can determine what you need to know using a digital input, or switch. Unlike analog transducers that sense continuous variables such as pressure and temperature, many transducers provide an output that is one of two states: high or low, open or closed. For instance, if a pressure is too high or a temperature too low, such that it falls outside a given range, it triggers the opening or closure of a switch. Since these types of inputs and outputs already exist in the binary language of computers, they are much easier for microprocessor-based data acquisition systems to deal with than analog signals. Because acquiring an analog signal is more complex than acquiring a digital one, analog I/O channels also are more expensive. Hence, if digital I/O is adequate, do not bother with analog. However, if you need to read a range of states, a digital I/O will not be expressive enough.

Digital Input

Digital inputs are either in one of two states: off or on. If voltage is flowing, the circuit is on (this is read as HIGH), and if it’s not flowing, the circuit is off (read as LOW). To make a digital circuit, you need a circuit, and a variable conductor like a switch which can either complete the circuit, or not.

In the above diagram, you add the resistor to resist the current flow. When the switch is closed, the current will follow the path of least resistance to the microcontroller pin, sending it a signal like you want it to do (the resistor in this diagram acts as a pulldown resistor). You need the connection to ground as a reference point, and the resistor also prevents a power-to-ground short circuit.

In the Arduino IDE, you declare the pin to be an input at the top of your program. Then you read it for the values 1 or 0, like so:

// give the pin numbers names:
const int inputPin = 2;
const int outputPin = 3;
void setup() {
 // declare inputPin to be an input:
 pinMode(inputPin, INPUT);
 pinMode(outputPin, OUTPUT);
}

void loop() {
 if (digitalRead(inputPin) == 1) {
 	digitalWrite(outputPin, HIGH);
 }
}

 

Digital Output

The simplest control you can use over an electrical device is digital output. In this case, you would either turn something off, or on. The diagram below is a digital output controlling an LED:

In the Arduino IDE, you declare the pin an output at the top of the program, then in the body of the program you use the commands HIGH and LOW to set the pin high or low, as we’ve seen above.

Here’s a simple blinking LED program, where the LED is attached to pin 13:

//give pin number a name:
const int LEDpin = 13;

void setup() {
 pinMode(LEDPin, OUTPUT);
}

void loop() {
 digitalWrite(LEDpin, HIGH);
 delay(1000);
 digitalWrite(LEDpin, LOW);
 delay(1000);
}