EAZYLife STEM LAB · MODULE 17

Microcontrollers and Embedded Programming

Explore how a microcontroller reads inputs, processes instructions and controls outputs. Learn the hardware architecture behind Arduino-style development, then write responsive programs using GPIO, ADC, PWM, timers and interrupts.

Free open lesson Microcontroller fundamentals Practical Arduino code
INPUT · PROCESS · OUTPUT
01 · WHAT IS A MICROCONTROLLER?

A small computer built to control a system

A microcontroller (MCU) combines a processor core, memory and peripheral hardware in one integrated circuit. It runs a program and interacts with the physical world through pins and built-in interfaces. Unlike a general-purpose computer, it is usually designed for a defined control task, often with limited memory, power and processing capacity.

Inside a typical microcontroller

MICROCONTROLLERCPU corefetch · decode · executeFlashRAMGPIOADCTimersUART / SPI / I²CClock sourcePower and resetPhysical pinsPeripheral signals

Conceptual architecture only. The exact peripherals, memory sizes, pin functions and internal bus arrangement depend on the MCU family and device.

Microcontroller vs microprocessor

A microprocessor is primarily a CPU and commonly relies on external memory and peripherals. A microcontroller integrates a CPU with memory and control peripherals for embedded tasks. Modern devices blur this distinction, so compare the actual device architecture rather than relying only on the label.

Embedded system

An embedded system combines hardware and firmware to perform a particular function: a motor controller, digital thermostat, smart meter, appliance controller or robot. It may also include sensors, power electronics, communications and a user interface.

02 · THE PROGRAM EXECUTION CYCLE

Instructions become actions through a repeating cycle

The processor fetches an instruction from program memory, decodes it and executes it. It repeats this process, while hardware peripherals can perform timed or communication tasks alongside the CPU. A reset starts execution from the device's defined reset entry point.

From reset to running firmware

ResetInitialisesetup()Read inputsProcessUpdateoutputsloop() repeats while the program runsPower / reset

Arduino sketch structure

void setup() {
  // Runs once after reset
  pinMode(LED_BUILTIN, OUTPUT);
}

void loop() {
  // Repeats while the board is running
  digitalWrite(LED_BUILTIN, HIGH);
  delay(500);
  digitalWrite(LED_BUILTIN, LOW);
  delay(500);
}

The Arduino core provides startup code and a framework that calls setup() once, then loop() repeatedly. Other MCU development environments may use a different entry point and startup sequence.

Firmware is more than the sketch

Firmware includes the compiled program and may depend on startup code, libraries, configuration bits, bootloader and device-specific drivers. A bootloader is a small program that can help load application firmware; not every MCU uses one in the same way.

03 · DIGITAL INPUTS AND OUTPUTS

GPIO connects firmware to electrical signals

General-purpose input/output pins can be configured to read a logic state or drive a logic output. A GPIO pin is not a power supply: it has voltage, current, timing and protection limits stated in the device datasheet.

Input and output connection examples

MCUDigital inputDigital output10kGND+V logicRLEDGNDButton to GND

The drawing is a functional connection concept. Select the resistor and supply from the LED and MCU ratings. A button input needs a defined pull-up or pull-down state.

Digital input

const byte buttonPin = 2;
const byte ledPin = LED_BUILTIN;

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

void loop() {
  bool pressed = digitalRead(buttonPin) == LOW;
  digitalWrite(ledPin, pressed ? HIGH : LOW);
}

With INPUT_PULLUP, the switch connects the input to ground when pressed, so the logic is active-low.

Electrical limits matter

  • Check per-pin current, total port current and total device current limits.
  • Use a transistor or driver for motors, relays, lamps and other loads beyond GPIO capability.
  • Confirm whether a pin is 5 V tolerant before applying a 5 V signal.
  • Some pins have special startup, boot or peripheral functions.
04 · ADC, PWM AND TIMERS

Measure analogue levels and create timed outputs

Many MCUs include an analogue-to-digital converter (ADC), which converts a voltage into a number. PWM produces a repeating digital waveform whose duty cycle can control average power delivered to a suitable load. Timers provide accurate time bases for events, pulse generation and measurement.

ADC: voltage becomes a number

ADCsample / convert512Vindigital code

For an ideal N-bit ADC with 2ᴺ codes, the approximate code step is reference span divided by 2ᴺ. Actual transfer functions, endpoint conventions, noise and accuracy vary by MCU.

const int raw = analogRead(A0);
Serial.println(raw);

PWM: control duty cycle

HIGH timeDuty cycle = HIGH / period

Use PWM pins and frequency appropriate to the load. Motors may need a driver, flyback protection and a separate supply. LED brightness perception is not perfectly linear with duty cycle.

const byte pwmPin = 9;
void setup() { pinMode(pwmPin, OUTPUT); }
void loop() {
  analogWrite(pwmPin, 128); // board-dependent scale
}

Timers provide hardware timekeeping

A timer counts clock ticks, often with a selectable prescaler. When it reaches a programmed value or overflows, it can set a flag, trigger an interrupt, or update an output pin. Timer channels may also capture input edges or generate PWM. Using a timer peripheral is usually more precise and efficient than repeatedly counting software instructions.

05 · NON-BLOCKING PROGRAM DESIGN

Use time without freezing the whole program

delay() is useful for the first blink experiment, but it pauses the sketch's normal loop while waiting. During a long delay, the program may fail to respond promptly to buttons, sensors or communication tasks. The millis() function supports cooperative timing without intentionally blocking the loop.

Non-blocking LED blink using millis()

const byte ledPin = LED_BUILTIN;
const unsigned long interval = 500;
unsigned long previous = 0;
bool ledState = false;

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

void loop() {
  const unsigned long now = millis();

  if (now - previous >= interval) {
    previous = now;
    ledState = !ledState;
    digitalWrite(ledPin, ledState);
  }

  // Read sensors, update outputs and handle communication here.
}

Unsigned subtraction makes this elapsed-time pattern safe across the millis() counter rollover, provided the interval is within the supported range. It is cooperative scheduling, not a guarantee of hard real-time execution.

Debounce a mechanical button

Contacts can bounce between open and closed for a short period. A simple software debounce accepts a new state only after it remains unchanged for a chosen interval. The correct interval depends on the switch and application.

Use a state machine

Represent an application as named states such as IDLE, RUNNING, PAUSED and FAULT. Define which events cause transitions. This keeps behaviour easier to test than deeply nested delay-driven code.

06 · INTERRUPTS AND EVENT-DRIVEN WORK

Respond to events without constantly polling

An interrupt temporarily diverts execution to a short interrupt service routine (ISR) when a configured event occurs. Common sources include timer events, external pin changes, ADC completion and communication peripherals. Interrupts are powerful, but careless ISR code can create timing bugs.

External interrupt: count button edges

Button / sensoredge eventInterrupt logicinvoke short ISREvent countershared dataMain loop safely reads and processes the count
volatile unsigned long edgeCount = 0;

void onEdge() {
  edgeCount++; // Keep the ISR short
}

void setup() {
  Serial.begin(9600);
  pinMode(2, INPUT_PULLUP);
  attachInterrupt(digitalPinToInterrupt(2), onEdge, FALLING);
}

void loop() {
  noInterrupts();
  unsigned long snapshot = edgeCount;
  interrupts();

  Serial.println(snapshot);
  delay(250);
}

This is an introductory event-counter example, not a complete debounced button counter. On some boards, multi-byte values need an atomic read as shown. Confirm interrupt-capable pins and API support for your exact board.

Good ISR rules

  • Keep the routine short and predictable.
  • Avoid delay(), long loops, blocking serial output and dynamic memory allocation.
  • Share data with the main program carefully; volatile alone does not make multi-byte access atomic.
  • Use hardware or software debouncing for mechanical switches.
  • Check which functions are safe inside an ISR on the selected platform.

Polling or interrupt?

Polling is simple and can be reliable when the loop runs quickly enough and no event can be missed. Interrupts suit events that need prompt capture or occur asynchronously. They are not automatically better for every input.

07 · MEMORY AND DATA

Know where your program stores information

MemoryTypical purposeWhat to remember
Flash / program memoryStores firmware and constants on many MCUsUsually non-volatile; capacity and write endurance depend on device.
SRAM / RAMVariables, stack, buffers and runtime stateVolatile; lost when power is removed. Small MCUs can run out quickly.
EEPROM or emulated non-volatile storageSettings and small values retained across resetsWrites have endurance and timing limits; avoid writing continuously in a fast loop.

Data types and overflow

Choose types deliberately. An 8-bit unsigned value stores 0–255; a 16-bit unsigned value stores 0–65,535. Exact widths and the size of int vary by architecture. Integer overflow, signedness and implicit conversions can cause unexpected results.

Memory-conscious habits

  • Use appropriately sized variables and buffers.
  • Avoid large local arrays on a small stack.
  • Check string and serial-buffer usage.
  • Do not assume a pointer remains valid after its storage ends.
  • Use non-volatile storage only when persistence is needed.
08 · PRACTICAL BUILD

Build a responsive sensor-controlled indicator

Combine concepts from the previous analogue and digital sensor modules: read a potentiometer with the ADC, control LED brightness with PWM, and use a button to switch between two operating modes. This low-voltage exercise demonstrates input, processing, state and output in one small embedded application.

Connection diagram

Arduino Uno*A0 · analogue inputD2 · button inputD9 · PWM output5 V10 kΩ potGNDSWGND330Ω*GNDPot wiperLED path

*Example for a 5 V Arduino Uno-compatible board. Confirm the exact board's pinout and voltage. Potentiometer outer terminals go to 5 V and GND, wiper to A0. Button connects D2 to GND. LED polarity is anode toward the resistor/PWM pin and cathode to GND. A 330 Ω resistor is an example; calculate it for the actual LED and board. Use the board's built-in LED if unsure.

Parts and wiring

  • Arduino Uno-compatible 5 V board and USB cable.
  • 10 kΩ potentiometer, 6 mm push button and breadboard.
  • LED and suitable current-limiting resistor, or use the onboard LED.
  • Connect potentiometer outer legs to 5 V and GND, centre wiper to A0.
  • Connect button between D2 and GND; firmware enables INPUT_PULLUP.
  • Connect external LED from D9 through its resistor to GND, observing polarity.

Upload this sketch

const byte potPin = A0;
const byte buttonPin = 2;
const byte ledPin = 9;

bool invertMode = false;
bool lastButton = HIGH;
bool stableButton = HIGH;
unsigned long lastChange = 0;
const unsigned long debounceMs = 35;

void setup() {
  pinMode(buttonPin, INPUT_PULLUP);
  pinMode(ledPin, OUTPUT);
  Serial.begin(9600);
}

void loop() {
  bool reading = digitalRead(buttonPin);
  if (reading != lastButton) {
    lastChange = millis();
    lastButton = reading;
  }
  if (millis() - lastChange >= debounceMs &&
      reading != stableButton) {
    stableButton = reading;
    if (stableButton == LOW) invertMode = !invertMode;
  }

  int raw = analogRead(potPin);
  int level = map(raw, 0, 1023, 0, 255);
  if (invertMode) level = 255 - level;
  analogWrite(ledPin, level);

  Serial.print("ADC: ");
  Serial.print(raw);
  Serial.print("  PWM: ");
  Serial.print(level);
  Serial.print("  Mode: ");
  Serial.println(invertMode ? "INVERT" : "NORMAL");
}

The sketch assumes the classic 10-bit ADC and 8-bit analogWrite scale used by a typical Uno. Other boards may use different ADC resolution, PWM API, pin capability and voltage.

Test and record

  1. Turn the potentiometer slowly and observe the serial ADC value and LED brightness.
  2. Press the button once. The LED response should invert: turning the potentiometer now produces the opposite brightness trend.
  3. Observe whether button bounce causes multiple toggles; adjust debounce time only after measuring behaviour.
  4. Record the minimum and maximum ADC values and compare them with the ideal range.
  5. Explain which work is done by the CPU and which is handled by ADC and PWM peripherals.
09 · TROUBLESHOOTING AND RELIABILITY

Make the program predictable and maintainable

Board does not run the sketch

Check selected board and processor, USB cable/data connection, port, bootloader requirements, board power and compile errors. Confirm that the correct board package and upload method are selected.

Input values jump or stick

Check common ground, sensor wiring, ADC input limits, reference voltage, loose connections and noise. A floating analogue input has no stable defined voltage.

LED or PWM does not respond

Confirm the pin supports PWM on that board, the LED polarity and resistor, output mode, supply and whether another peripheral claims the pin.

Timing drifts or tasks are missed

Look for long blocking delays, slow serial printing, heavy calculations, interrupt load and timing assumptions. Use hardware timers or a suitable real-time design where deadlines require it.

Random reset or unstable operation

Investigate supply droop, motor/relay transients, grounding, decoupling, watchdog resets, stack/heap use and brown-out behaviour. Separate noisy load power from logic supply where appropriate.

Firmware becomes hard to extend

Separate input reading, decision logic and output updates. Use named constants, small functions, explicit states, clear units and comments that explain why rather than restating the code.

10 · SAFETY AND KNOWLEDGE CHECK

Respect the limits of the controller

Practical safety

  • Power down before changing connections; inspect for shorts and reversed polarity.
  • Keep all beginner practicals at extra-low voltage.
  • Never exceed pin voltage, current, injection-current or absolute maximum ratings.
  • Use a suitable transistor, MOSFET, relay driver or motor driver for external loads.
  • Use flyback protection for inductive loads where required by the driver design.
  • Do not connect motors, relays or lamps directly to GPIO pins.
  • Use ESD precautions and check the exact board and component datasheets.

Design habits worth keeping

Write down the MCU part number, board revision, supply range, pin assignments, clock configuration, peripheral settings, library versions and firmware revision. Test failure conditions as well as the happy path. A prototype is not automatically a safety-certified controller.

1. What is integrated into a typical microcontroller?

2. Why is millis()-based timing useful?

3. What should an interrupt service routine generally do?

4. Can a GPIO pin directly power a motor?

KEEP LEARNING · GO FURTHER

Free to learn. More support when you need it.

Explore these open lessons at your own pace. For personalised explanations, project-specific troubleshooting, guided practical training or masterclasses, EazyLife offers paid support tailored to your learning goals.

Free or sponsored lesson referrals may be available through active programmes; they are not guaranteed.

Enquire about guidance