Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 36 ยท Microcontrollers and Boards

Arduino Programming Basics

Learn Arduino-style firmware: setup and loop, digitalWrite, analogRead, Serial, non-blocking timing with millis, libraries, state machines and a simulator.

The Arduino framework made microcontrollers friendly: a few functions, a simple editor and thousands of ready libraries. The same programming model runs on AVR boards, ESP32, RP2040, STM32 and more, so what you learn here applies to most hobby and many commercial IoT devices. The code is C++, but you rarely need advanced C++ features.

The listings are read-only because a browser cannot talk to real hardware. After each one you get a runnable Python simulation of the same logic, so you can observe the behaviour that matters, especially timing.

The anatomy of a sketch

An Arduino program is a sketch with two required functions:

C++
const int LED_PIN = 13;

void setup() {                 // runs once at power-up or reset
  pinMode(LED_PIN, OUTPUT);
  Serial.begin(115200);
}

void loop() {                  // runs forever, over and over
  digitalWrite(LED_PIN, HIGH);
  delay(500);
  digitalWrite(LED_PIN, LOW);
  delay(500);
  Serial.println("blink");
}

setup() configures pins and starts services. loop() is the heart of the program; the framework calls it endlessly. There is no main() visible, no operating system and no "exit": the chip just keeps running until you cut the power.

Core functions

Function What it does
pinMode(pin, mode) INPUT, OUTPUT, INPUT_PULLUP
digitalWrite(pin, level) Set a pin HIGH (3.3/5 V) or LOW (0 V)
digitalRead(pin) Read HIGH or LOW
analogRead(pin) Read an ADC value (0-1023 on Uno, 0-4095 on ESP32)
analogWrite(pin, 0-255) PWM output (ledcWrite on ESP32 cores older than 3.x)
delay(ms) Pause the whole program
millis() Milliseconds since power-up
Serial.print / println Send text to the computer over USB

A reading and printing sketch:

C++
const int SENSOR_PIN = A0;

void setup() { Serial.begin(115200); }

void loop() {
  int raw = analogRead(SENSOR_PIN);
  float volts = raw * (5.0 / 1023.0);
  Serial.print("raw=");   Serial.print(raw);
  Serial.print(" volts="); Serial.println(volts, 2);
  delay(1000);
}

Use Serial.println generously while developing; it is the simplest debugging tool on a chip with no screen.

Data types and memory

  • int is 16-bit on AVR (-32768 to 32767) but 32-bit on ESP32. Use int32_t, uint8_t and friends when size matters.
  • unsigned long for millis() values.
  • Avoid the String class on small AVR boards: it fragments memory. Prefer char arrays.
  • const data can live in flash (PROGMEM on AVR) to save RAM.

The problem with delay()

delay(1000) freezes the program: nothing else, no button check, no network handling, runs for that second. A device that must do several things at once cannot use it. The fix is non-blocking timing with millis(): remember when you last did something and compare.

C++
unsigned long lastBlink = 0;
const unsigned long BLINK_MS = 500;
bool ledOn = false;

void loop() {
  unsigned long now = millis();
  if (now - lastBlink >= BLINK_MS) {      // unsigned subtraction handles rollover
    lastBlink = now;
    ledOn = !ledOn;
    digitalWrite(LED_PIN, ledOn);
  }
  checkButton();                          // runs thousands of times a second
}

The subtraction now - lastBlink stays correct even when millis() wraps around after about 49.7 days, because unsigned arithmetic wraps too.

The next simulation emulates a loop that runs with a millis() clock and handles two independent timers plus a button, without ever blocking.

Python Non-blocking timers with a simulated millis()

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

With delay(250) blinking, the 130 ms button press would have been missed or handled late. With millis() the program keeps reacting.

State machines

Real firmware is usually a state machine: the device is in one state at a time and moves between states on events. For example: IDLE -> MEASURING -> SENDING -> SLEEPING. State machines keep non-blocking code understandable and are easy to test.

Python A sensor node as a state machine

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Libraries and the build

The Arduino IDE, Arduino CLI and PlatformIO install libraries (DHT, Adafruit_Sensor, PubSubClient, Servo, Wire) and board packages (ESP32, STM32). You write #include <WiFi.h> and the toolchain handles compilation and uploading over USB. For larger projects, PlatformIO in VS Code gives better dependency management and unit testing; the code remains the same.

Reading a button properly

Use INPUT_PULLUP so the pin reads HIGH when open and LOW when pressed, with no external resistor:

C++
const int BUTTON = 2;
void setup() { pinMode(BUTTON, INPUT_PULLUP); Serial.begin(115200); }
void loop() {
  if (digitalRead(BUTTON) == LOW) {   // pressed
    Serial.println("pressed");
    delay(200);                       // crude debounce
  }
}

A better solution debounces with timing as in signal conditioning or uses an interrupt.

Common mistakes

  • Forgetting pinMode, so a pin does not behave as an output.
  • Using delay() everywhere and then wondering why buttons feel laggy.
  • Running out of RAM with big String objects or arrays.
  • Comparing floats with ==.
  • Printing too much on Serial in a time-critical loop.
  • Powering motors from the board's 5 V pin (use a separate supply).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. When does setup() run?

    setup() initializes pins and services once; loop() then repeats forever.
  2. 2. Why avoid delay() in programs that handle several tasks?

    During delay() the program cannot read buttons, sensors or network messages.
  3. 3. Why is "now - lastTime >= interval" safe when millis() rolls over?

    Unsigned arithmetic wraps modulo 2^32, so the elapsed time stays right across the rollover.
  4. 4. What does INPUT_PULLUP do?

    With the pull-up, the pin reads HIGH when open and LOW when the button connects it to ground.

Summary

  • A sketch has setup() (once) and loop() (forever) on top of simple pin and Serial functions.
  • Use millis() and state machines instead of delay() for responsive multi-tasking.
  • Mind integer sizes and RAM; prefer char arrays on tiny boards.
  • Libraries and board packages hide the toolchain; Serial printing is the main debugging tool.

Next: GPIO, PWM and Interrupts