Digital write

To set the value of a digital pin in the Arduino programming language, we use the digitalWrite() function. This function takes the following syntax:

digitalWrite(pin, value);

The digitalWrite() function accepts two parameters, where the first one is the pin number and the second is the value to set. We should use either HIGH or LOW when setting the value of a digital pin. The following code shows how to do this:

digitalWrite(LED_ONE, HIGH);
delay(500);
digitalWrite(LED_ONE, LOW);  
delay(500);

In the preceding code, we set the pin defined by the LED_ONE constant too HIGH and then pause for half a second. The delay() function in the Arduino programming language pauses the execution of the sketch for a certain amount of time. The time for this function is in milliseconds. After the delay() function we then set the pin defined by the LED_ONE constant too LOW and wait another half a second before looping back to the beginning.

The previous code can be used in the loop() function to blink an LED; however, before we do that we need to define the LED_ONE constant and also set the pin mode. Let's look at the full sketch required to blink an LED.

#define LED_ONE 11

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

void loop() {
  digitalWrite(LED_ONE, HIGH);
  delay(500);
  digitalWrite(LED_ONE, LOW);
  delay(500);
}

This code starts off by defining the LED_ONE constant and setting to 11. The pin mode for the LED_ONE pin is then set in the setup() function. Finally, the code that will cause the LED to blink is added to the loop() function. If you connect the prototype that we developed in Chapter 4, Basic Prototyping and ran this code, you should see one of the LEDs blinking.

Now that we know how to write to a digital pin, let's see how we can read the value of one.