Arduino Tutorial

By LiterallyTheOne

1: GPIO

Arduino Tutorial, GPIO

Introduction

  • Previous tutorial: blinking LED
  • This tutorial: GPIO
By Ramin Zarebidoky (LiterallyTheOne)
Arduino Tutorial, GPIO

What is GPIO?

  • General Purpose Input/Output
  • Input: We read from it
  • Output: We write to it
By Ramin Zarebidoky (LiterallyTheOne)
Arduino Tutorial, GPIO

GPIO Pins

  • 14 Digital pins:
    • 0-13 (shown in red)
  • 6 Analog pins:
    • A0-A5 (shown in yellow)
By Ramin Zarebidoky (LiterallyTheOne)
Arduino Tutorial, GPIO

pinMode

pinMode(pin_number, mode);
  • pin_number: number of the pin that we want to change (e.g., 13)
  • mode: we can choose the mode of the pin; two of the choices are:
  • INPUT: 0
  • OUTPUT: 1
By Ramin Zarebidoky (LiterallyTheOne)
Arduino Tutorial, GPIO

pinMode example

  • pin 13 as output:
pinMode(13, OUTPUT);
  • pin 3 as input:
pinMode(3, INPUT);
By Ramin Zarebidoky (LiterallyTheOne)
Arduino Tutorial, GPIO

Add LED and Key

led and key

By Ramin Zarebidoky (LiterallyTheOne)
Arduino Tutorial, GPIO

Setup

pinMode(13, OUTPUT);
pinMode(2, INPUT);
By Ramin Zarebidoky (LiterallyTheOne)
Arduino Tutorial, GPIO

Variables

bool led_state = false;
bool button_pressed = false;
By Ramin Zarebidoky (LiterallyTheOne)
Arduino Tutorial, GPIO

Logic

button_pressed = digitalRead(2);
if (button_pressed)
{
    led_state = !led_state;
    digitalWrite(13, led_state);
    delay(500);
}
By Ramin Zarebidoky (LiterallyTheOne)
Arduino Tutorial, GPIO

Full code

#include <Arduino.h>

bool led_state = false;
bool button_pressed = false;

void setup()
{
  pinMode(13, OUTPUT);
  pinMode(2, INPUT);
}

void loop()
{
  button_pressed = digitalRead(2);
  if (button_pressed)
  {
    led_state = !led_state;
    digitalWrite(13, led_state);
    delay(500);
  }
}
By Ramin Zarebidoky (LiterallyTheOne)
Arduino Tutorial, GPIO

Result

By Ramin Zarebidoky (LiterallyTheOne)
Arduino Tutorial, GPIO

3 LEDs

By Ramin Zarebidoky (LiterallyTheOne)
Arduino Tutorial, GPIO

Add another button

By Ramin Zarebidoky (LiterallyTheOne)
Arduino Tutorial, GPIO

By Ramin Zarebidoky (LiterallyTheOne)