Arduino Digital input and output (GPIO pins)

Arduino boards have a range of digital input/output (GPIO) pins that can be used to control and communicate with various electronic components. Here’s an overview of how to use digital input and output with Arduino:

1. Digital output: Digital output pins can be used to control LEDs, motors, relays, and other electronic components that operate with a simple on/off state. To use a digital output pin, you first need to set it as an output using the pinMode() function, and then you can write a digital value to the pin using the digitalWrite() function. A value of HIGH (5 volts) turns the pin on, and a value of LOW (0 volts) turns it off.

Here’s an example code to turn an LED on and off using a digital output pin:

int ledPin = 13;

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

void loop() {
  digitalWrite(ledPin, HIGH); // Turn the LED on
  delay(1000); // Wait for 1 second
  digitalWrite(ledPin, LOW); // Turn the LED off
  delay(1000); // Wait for 1 second
}

2. Digital input: Digital input pins can be used to read the state of switches, buttons, and other digital sensors. To use a digital input pin, you first need to set it as an input using the pinMode() function, and then you can read its state using the digitalRead() function. A value of HIGH means that the pin is receiving 5 volts, and a value of LOW means that the pin is receiving 0 volts.

Here’s an example code to read the state of a button using a digital input pin:

int buttonPin = 2;
int ledPin = 13;

void setup() {
  pinMode(buttonPin, INPUT);
  pinMode(ledPin, OUTPUT);
}

void loop() {
  int buttonState = digitalRead(buttonPin);
  if (buttonState == HIGH) {
    digitalWrite(ledPin, HIGH); // Turn the LED on
  } else {
    digitalWrite(ledPin, LOW); // Turn the LED off
  }
}

3. PWM output: Some digital output pins on Arduino boards can be used to generate Pulse-Width Modulation (PWM) signals, which can be used to control the brightness of LEDs, the speed of motors, and other analog components. To use PWM output, you need to set the pin as an output using the pinMode() function, and then you can write an analog value to the pin using the analogWrite() function. The analog value can range from 0 (0 volts) to 255 (5 volts).

Here’s an example code to control the brightness of an LED using PWM output:

int ledPin = 9;

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

void loop() {
  for (int brightness = 0; brightness <= 255; brightness++) {
    analogWrite(ledPin, brightness);
    delay(10);
  }
  for (int brightness = 255; brightness >= 0; brightness--) {
    analogWrite(ledPin, brightness);
    delay(10);
  }
}

Overall, digital input/output is a fundamental aspect of using Arduino boards, and can be used to control and communicate with a wide range of electronic components.