Module 6

Getting started with Arduino

Quick-reference revision notes for parents.

6.1 Getting started — first circuit (LED)

Every sketch has two main functions:

void setup() {
  // runs once when the board starts
  pinMode(13, OUTPUT);
}

void loop() {
  // runs over and over forever
  digitalWrite(13, HIGH);
  delay(1000);
  digitalWrite(13, LOW);
  delay(1000);
}

6.2 Breadboards and buttons

int buttonPin = 2;

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

void loop() {
  if (digitalRead(buttonPin) == HIGH) {
    digitalWrite(13, HIGH);
  } else {
    digitalWrite(13, LOW);
  }
}

6.3 Latching buttons using variables

A latch remembers a state — e.g. one press turns the LED on, the next turns it off, even though the button is only momentarily pushed.

int ledState = LOW;

void loop() {
  if (digitalRead(buttonPin) == HIGH) {
    ledState = !ledState;     // flip
    digitalWrite(13, ledState);
    delay(300);               // debounce
  }
}

Variables in Arduino C: int, bool, float, String. Always declare with a type.

6.4 Analogue input and output

Analogue input

Analogue output (PWM)

6.5 Subroutines

Pull repeated code into a function, just like in Python:

void blink(int pin, int times) {
  for (int i = 0; i < times; i++) {
    digitalWrite(pin, HIGH);
    delay(200);
    digitalWrite(pin, LOW);
    delay(200);
  }
}

void loop() {
  blink(13, 3);
  delay(1000);
}

6.6 Making a useful system

Combine inputs, outputs and logic to build something real.

Example project — automatic light

Read the LDR. If it's dark (analogRead value below threshold), turn the LED on. Otherwise turn it off. A simple "smart" night light.

Quick reference

← Back All modules Next → Practice questions