Arduino Toggle Pin

This tutorial will discuss toggling a digital pin using the digitalWrite() function in Arduino.

Arduino Toggle Pin

Arduino digital pin has three states: high, low, and floating. In the high state, the voltage of the pin will be 5 and low state; the voltage will be 0.

At the floating state, the voltage of the pin will be between 0 to 5. By default, all the pins are at a floating state, and if we read a pin value, it will give us a floating value.

We can use the digitalRead() function to read a digital pin and pass the pin number inside the function. We can use the digitalWrtie() function to write a digital pin and pass the pin number inside the function.

Before we start reading or writing a pin, we must set its mode to input or output. We can use the pinMode() function to set the mode of a pin.

The first argument of the pinMode() function is the pin number, and the second argument is the mode like output or input. For example, let’s toggle a digital pin 9 and attach a LED with it, which will toggle.

See the code below.

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

void loop() {
  digitalWrite(9, !digitalRead(9));
  delay(1000);
}

In the above code, we are toggling pin 9 of Arduino UNO with a one-second delay. The pin will stay HIGH for one second, and then it will change its state to LOW and maintain that state for one second.

We have used the ! symbol in the above code, which toggles the pin state HIGH to LOW and LOW to HIGH. We read the pin 9 status; toggle it using the ! symbol, and then write it to pin 9.

If we attach a LED with a resistor to pin 9, it will start blinking with a one-second delay. If we don’t add a delay, the LED’s blinking will be so fast that we will not see it physically with our eyes.

The toggle or blinking speed depends on the frequencies of the Arduino board. Different Arduino boards have different operating frequencies, like 8 MHz and 6 MHz.