Week 1Meet the microcontroller
90 min
Beginner

Lesson 1: What is a microcontroller?

Start at the very beginning: what an embedded system is, how a microcontroller differs from a microprocessor, and what lives inside the ATmega328P.

Lesson introduction

Many devices around us appear simple: a washing machine changes its cycle, a car detects an open door, and a thermostat switches heating on when a room becomes cold. Inside each device, a small computer repeatedly reads information, follows instructions and controls something physical. That small computer is often a microcontroller.

In this course, we will use the ATmega328P microcontroller on the Arduino Uno board. Arduino functions will help us begin quickly. Later, we will look below those functions and control the ATmega328P through its registers. This means you will learn both how to make a project work and what happens inside the chip.

A microcontroller inside an embedded system — tap to enlarge

Learning objectives

After this lesson, you should be able to:

  1. Define a microcontroller and an embedded system.
  2. Identify inputs, processing and outputs in real products.
  3. Explain the difference between a microcontroller and a microprocessor.
  4. Explain the difference between an Arduino Uno board and its ATmega328P chip.
  5. Describe the jobs of the CPU, ALU, clock, buses, memories and peripherals.
  6. Explain Flash, SRAM and EEPROM using simple examples.
  7. Explain what registers are and why software changes them.
  8. Describe the fetch–decode–execute cycle.
  9. Connect an Arduino Uno safely and run a simple observation program.

Before you begin

You do not need previous microcontroller knowledge. For the practical activity you need:

  • Arduino Uno or compatible ATmega328P board
  • Correct USB cable
  • Computer with Arduino IDE installed

No breadboard components are required in Lesson 1.


1. What is a microcontroller?

A microcontroller, often shortened to MCU, is a small computer built into a single integrated circuit. It normally contains:

  • a processor that executes instructions;
  • memory that holds the program and working data;
  • input/output hardware for communicating with the outside world;
  • peripherals for jobs such as timing, analog measurement and serial communication.

A microcontroller is designed mainly to control a particular product or process. It does not normally run many general applications like a laptop. It repeatedly performs the smaller set of tasks required by its embedded program.

Simple analogy: a small control room

Imagine a building control room:

  • Sensors report temperature, smoke and movement.
  • A controller checks the reports and follows rules.
  • Outputs operate alarms, lights, fans or doors.

A microcontroller plays the role of that controller. Its program contains the rules.

Sense → Process → Act

Most beginner embedded systems can be understood using three stages:

StageMeaningSmart-room example
InputReceive informationLDR reports darkness
ProcessFollow the program and decideCompare light reading with a threshold
OutputCause an actionSwitch on an LED lamp

This pattern can run continuously, thousands or millions of times.

Check your understanding

A fire-alarm system has a smoke sensor, microcontroller and buzzer.

  • Input: smoke sensor
  • Processing: microcontroller checks whether the reading exceeds a safe limit
  • Output: buzzer and warning light

2. What is an embedded system?

An embedded system is a complete electronic system designed to perform one or several dedicated functions as part of a larger product.

The microcontroller is an important component, but it is not the whole embedded system.

Embedded system = microcontroller + program + power + inputs + outputs + supporting electronics

Real-world examples

ProductPossible inputsProcessing decisionPossible outputs
Washing machineDoor switch, water-level sensorIs the door locked and water level correct?Motor, valve, display
Car parking aidUltrasonic sensorsHow far away is the obstacle?Beeps or dashboard image
Digital thermostatTemperature sensor, buttonsIs the room colder than the selected value?Heater relay, display
Smart irrigationSoil-moisture sensor, clockIs the soil dry during an allowed watering time?Water valve
Fitness trackerMotion and heart-rate sensorsCount movement and calculate measurementsScreen, vibration, wireless data

Think like an engineer: Do not start by asking, “Which code should I write?” Start by identifying inputs, decisions and outputs.


3. Microcontroller versus microprocessor

The two terms sound similar, but they normally describe different design approaches.

FeatureMicrocontrollerMicroprocessor
Typical purposeDedicated control taskGeneral computing
CPUOn the chipOn the main processor chip
RAM and program storageUsually included on chip in smaller amountsOften uses larger external memory chips
GPIO, ADC and timersCommonly includedOften needs supporting controller chips
Power useUsually lowerUsually higher
Typical softwareOne firmware application or small real-time systemFull operating system and many applications
Example useSensor node, appliance, motor controllerLaptop, desktop, powerful single-board computer

This is a general comparison, not an absolute rule. Modern devices can blur the boundary. For example, some powerful microcontrollers run small operating systems, and some processors include many peripherals.

Arduino Uno and Raspberry Pi are not the same type of device

  • An Arduino Uno uses a microcontroller and is excellent for direct, predictable control of pins and hardware.
  • A typical Raspberry Pi is a small computer with a microprocessor-class system, external memory and an operating system.

Neither is automatically “better.” The correct choice depends on the task.


4. Arduino Uno board versus ATmega328P chip

The ATmega328P microcontroller, a 28-pin DIP chip — tap to enlarge
Arduino Uno board with the ATmega328P chip in its socket — tap to enlarge
Arduino Uno board versus ATmega328P chip — tap to enlarge

The Arduino Uno is a development board. The ATmega328P is the main microcontroller that executes your application.

The Uno board adds useful supporting hardware:

  • USB connection for programming and serial communication;
  • power input and regulation;
  • 16 MHz clock circuitry;
  • reset circuit and reset button;
  • pin headers that make connections easier;
  • indicator LEDs;
  • an uploaded bootloader that helps receive programs.

Why this distinction matters

When you write:

digitalWrite(13, HIGH);

the Arduino board does not “understand C++” by itself. The code is compiled into machine instructions. The ATmega328P executes those instructions, and its GPIO hardware changes an electrical output connected to Arduino digital pin 13.

Important Uno R3 facts

ItemValue
Main microcontrollerATmega328P
Typical clock16 MHz
Digital I/O pins exposed by board14
PWM-capable digital pins6
Analog input pins exposed by board6
Flash memory32 KB; part is used by bootloader
SRAM2 KB
EEPROM1 KB

Important: Arduino pin numbers are board-friendly names. Inside the ATmega328P, pins are organised into ports such as PORTB, PORTC and PORTD. We will map these in Lesson 2 and control them in Lesson 5.


5. Inside the ATmega328P

The ATmega328P is an 8-bit AVR RISC microcontroller. “8-bit” means its core is designed to work naturally with eight-bit data. “RISC” describes an instruction-set design using relatively simple, efficient instructions.

Simplified ATmega328P architecture — tap to enlarge

The diagram is simplified for learning. Let us examine each major block.

5.1 CPU — the instruction executor

The Central Processing Unit (CPU) reads and executes machine instructions. It coordinates other parts of the microcontroller.

The CPU repeatedly performs operations such as:

  • load a value from memory;
  • add or compare values;
  • move data between registers;
  • branch to another instruction;
  • read a peripheral register;
  • change an output register.

5.2 ALU — the calculator and logic worker

The Arithmetic Logic Unit (ALU) performs operations such as:

  • addition and subtraction;
  • AND, OR and XOR logic;
  • comparisons;
  • shifting bits left or right.

If your program checks temperature > 30, machine instructions cause values to enter the CPU, the ALU performs a comparison, and status flags record the result.

5.3 Working registers

The AVR CPU has 32 general-purpose 8-bit working registers, named R0 to R31. They are very fast storage locations close to the ALU.

These CPU working registers are not the same as peripheral registers such as GPIO control registers. Both are called registers because they are small hardware storage locations, but their purposes differ.

5.4 Program Counter

The Program Counter (PC) identifies the next program instruction to execute. It normally advances as instructions run. A jump, function call or interrupt can change it.

Think of the PC as a bookmark showing which instruction comes next.

5.5 Stack Pointer and stack

The Stack Pointer (SP) points to the current top of the stack in SRAM. The stack temporarily holds information such as return addresses for function calls and saved CPU data.

If SRAM becomes exhausted, the stack can collide with other data and the program may behave unpredictably. This is one reason embedded programmers care about memory use.

5.6 Status Register (SREG)

SREG is the AVR Status Register. Its bits store CPU status information produced by operations.

BitNameSimple meaning
7IGlobal interrupt enable
6TBit-copy storage
5HHalf-carry flag
4SSigned-test result derived from other flags
3VTwo's-complement overflow flag
2NNegative-result flag
1ZZero-result flag
0CCarry flag

You do not need to memorise every flag now. The important idea is this: an arithmetic or logic operation can automatically change status bits, and later instructions can make decisions using them.


6. Clock: the system's pace

A microcontroller needs a clock signal to sequence its operations. The Uno normally runs the ATmega328P at 16 MHz.

16 MHz = 16,000,000 clock cycles per second

The duration of one clock cycle is:

cycle time = 1 / frequency
           = 1 / 16,000,000
           = 0.0000000625 seconds
           = 62.5 nanoseconds

This does not mean every Arduino statement finishes in 62.5 ns. A high-level statement becomes several machine instructions, and different instructions or library functions require different numbers of cycles.

Real-world analogy

Think of musicians following a conductor's beat. The clock provides a shared pace so internal actions happen in the correct order. It does not decide what the program does; the instructions decide that.


7. Memory: Flash, SRAM and EEPROM

Flash, SRAM and EEPROM comparison — tap to enlarge

7.1 Flash memory — the recipe book

Flash stores the compiled program instructions. It is non-volatile, meaning it keeps its contents when power is removed.

On the ATmega328P there are 32 KB of Flash. On a normal Uno, part is occupied by the bootloader, so the full amount is not available to the sketch.

7.2 SRAM — the work desk

SRAM holds temporary working information while the program runs:

  • variables;
  • arrays and buffers;
  • some temporary calculation values;
  • the stack.

The ATmega328P has 2 KB of SRAM. SRAM is volatile: its contents disappear when power is removed or the device resets.

7.3 EEPROM — the small notebook

EEPROM stores selected values that must survive power loss, such as a calibration value or saved user setting. The ATmega328P has 1 KB of EEPROM.

EEPROM is non-volatile, but it has limited write endurance. It should not be rewritten continuously inside a fast loop.

Memory example

Suppose we build a temperature controller:

  • Flash: program that measures temperature and controls a fan
  • SRAM: current reading, temporary average and program variables
  • EEPROM: user's preferred temperature setting that must survive power-off

8. Buses: internal paths for information

A bus is a group of electrical paths used to carry information between internal blocks.

Three useful conceptual categories are:

  • Data bus: carries values.
  • Address information: identifies the required location or peripheral.
  • Control signals: indicate actions such as read or write.

For example, when the CPU reads a GPIO input register, internal hardware identifies the register, performs a read and returns its current bits to the CPU.

The AVR architecture separates program memory and data memory into distinct spaces and paths. This Harvard-style organisation allows the CPU to work efficiently with program instructions and data.


9. Peripherals: specialised hardware helpers

A peripheral is a hardware block inside the microcontroller designed for a particular job.

PeripheralMain jobLater course use
GPIORead or create digital HIGH/LOW signalsLEDs and buttons
ADCConvert an analog voltage into a numberPotentiometer and LDR
Timer/counterCount clock events and create accurate timingPeriodic tasks
PWM hardwareProduce repeated pulses with controlled duty cycleLED brightness and motor speed
USARTSerial communicationSerial Monitor
SPIFast synchronous communicationDisplays and sensors
TWI/I²CTwo-wire addressed communicationMulti-device sensor bus
Interrupt controllerNotify CPU about eventsFast button or timer response
WatchdogReset system if software stops respondingReliability

Why hardware peripherals are valuable

Without a timer peripheral, the CPU would need to spend instructions counting time continuously. A timer can count in hardware while the CPU performs other work. The peripheral can later set a flag or request an interrupt.


10. What is a register?

A register is a very small hardware storage location inside the CPU or a peripheral. Most ATmega328P control registers are eight bits wide.

Each bit can behave like a tiny configuration switch or status indicator.

Bit position:  7 6 5 4 3 2 1 0
Register:      0 0 1 0 0 1 0 1

The binary value above is 00100101, which equals hexadecimal 0x25 and decimal 37.

Control register example

Later, we will use DDRB, the data-direction register for Port B. A bit set to 1 configures the corresponding port pin as an output; 0 configures it as an input.

DDRB = 00100000
             ↑
          bit 5 = 1

This configures PB5 as an output while other Port B pins remain inputs. On the Arduino Uno, PB5 corresponds to digital pin 13, which is connected to the built-in L LED circuit.

Register versus variable

Variable in SRAMHardware register
Mainly stores program dataOften controls hardware or reports hardware state
Created and used by softwarePhysically implemented inside CPU/peripheral
Changing it normally changes only stored dataChanging a control bit can immediately alter hardware behaviour

Core idea: Arduino functions eventually read or modify hardware registers. Register-level programming lets us control those registers more directly.


11. From your source code to running hardware

When you press Upload, several stages occur:

  1. You write human-readable Arduino C/C++ source code.
  2. The preprocessor and compiler translate it into lower-level object code.
  3. The linker combines your code with required Arduino core code and libraries.
  4. A machine-code image is produced for the ATmega328P.
  5. The upload tool communicates with the Uno's bootloader through the USB-to-serial path.
  6. Program bytes are written into Flash memory.
  7. The microcontroller resets.
  8. The bootloader finishes and your application starts.

Arduino sketches present setup() and loop(), but the supporting Arduino core supplies hidden startup code and a main() function. Conceptually, it behaves like this:

int main(void) {
    init();       // Prepare Arduino core services
    setup();      // Run the user's setup once

    while (true) {
        loop();   // Run the user's loop repeatedly
    }
}

This is a simplified explanation; exact core implementation details can vary by version.


12. Fetch–decode–execute cycle

Fetch decode execute cycle — tap to enlarge

After startup, the CPU repeatedly performs a cycle:

Step 1 — Fetch

The Program Counter indicates the next instruction. The CPU fetches that instruction from Flash.

Step 2 — Decode

The control logic determines what the instruction asks the CPU to do and which operands it needs.

Step 3 — Execute

The CPU performs the operation. It might use the ALU, move a value, change a register or jump to another instruction.

Step 4 — Continue

The Program Counter points to the appropriate next instruction and the process repeats.

AVR uses a pipelined design that can fetch the next instruction while the current instruction executes. Many AVR instructions therefore complete in one clock cycle, although not all do.

Example: turning an LED on

The high-level statement:

digitalWrite(LED_BUILTIN, HIGH);

does not travel directly to the LED. A simplified path is:

source statement
→ compiled AVR machine instructions
→ CPU fetches and executes instructions
→ GPIO output register is changed
→ output driver creates an electrical level
→ built-in LED circuit emits light

13. Practical activity — observe the whole system

Goal

Identify the main board parts, upload a program, observe startup and connect software events to physical board behaviour.

USB observation setup — tap to enlarge

Safety

  • Place the Uno on a dry, non-metallic surface.
  • Connect only the USB cable in this lesson.
  • Never place the powered board on loose metal objects.
  • If the board or cable becomes unusually hot, disconnect it.

Part A — identify the board

Before connecting power, locate:

  1. ATmega328P main microcontroller
  2. USB connector
  3. Reset button
  4. Built-in L LED
  5. ON power LED
  6. TX and RX communication LEDs
  7. Digital and analog pin headers
  8. Power header and GND pins

Board layouts vary slightly between official and compatible Uno boards.

Part B — prepare Arduino IDE

  1. Connect the Uno to the computer using USB.
  2. Open Arduino IDE.
  3. Choose Tools → Board → Arduino AVR Boards → Arduino Uno.
  4. Choose the correct port under Tools → Port.
  5. Open a new sketch.

Part C — upload the observation program

const uint8_t LED_PIN = LED_BUILTIN;

void setup() {
  pinMode(LED_PIN, OUTPUT);
  Serial.begin(9600);
  Serial.println("EMBEDLIX Lesson 1: setup runs once");
}

void loop() {
  Serial.println("loop: LED ON");
  digitalWrite(LED_PIN, HIGH);
  delay(1000);

  Serial.println("loop: LED OFF");
  digitalWrite(LED_PIN, LOW);
  delay(1000);
}

Upload the sketch. Open Serial Monitor and select 9600 baud.

Line-by-line explanation

const uint8_t LED_PIN = LED_BUILTIN;
  • const means our program should not change this name's value.
  • uint8_t is an unsigned eight-bit integer type.
  • LED_BUILTIN is supplied by the selected Arduino board definition.
void setup() {

Arduino calls setup() once after startup/reset.

pinMode(LED_PIN, OUTPUT);

This prepares the pin as a digital output. Internally, Arduino code eventually changes a GPIO direction register.

Serial.begin(9600);

This configures serial communication at 9600 bits per second. It involves the ATmega328P USART peripheral and Arduino library code.

Serial.println("EMBEDLIX Lesson 1: setup runs once");

This sends text through the serial system. You should see it once after reset.

void loop() {

Arduino calls loop() repeatedly.

digitalWrite(LED_PIN, HIGH);

This requests a HIGH output on the built-in LED pin. On a normal Uno, the built-in LED illuminates.

delay(1000);

Execution waits approximately 1000 ms. This is easy for a first experiment, but it blocks normal progress through loop(). We will later design non-blocking programs.

Expected observations

  • The ON LED indicates that the board receives power.
  • Communication LEDs may flash during upload.
  • The built-in L LED turns on for about one second and off for about one second.
  • The setup message appears once after reset.
  • The two loop messages repeat.

Press Reset

Press the reset button once. Observe that:

  1. program execution restarts;
  2. the setup message appears again;
  3. the repeating LED sequence begins again.

This demonstrates that reset restarts execution; it does not normally erase the program from Flash.

Observation table

Complete this table yourself:

EventLED/serial observationWhat probably happened inside?
USB connected
Upload started
Upload completed
Reset pressed
digitalWrite(HIGH) executed

14. Guided investigation

Change both delays from 1000 to 250.

Predict before uploading

  1. Will setup() run more often?
  2. Will the LED blink faster or slower?
  3. What will happen to the Serial Monitor messages?
  4. Does changing delay alter the clock frequency?

Explanation

  • setup() still runs once per reset.
  • The LED and messages change four times faster because each wait is 250 ms instead of 1000 ms.
  • The hardware clock remains 16 MHz. The program simply requests shorter waits.

The approximate full blink period is:

250 ms ON + 250 ms OFF = 500 ms = 0.5 s
frequency = 1 / period = 1 / 0.5 = 2 Hz

15. Common mistakes and troubleshooting

Board does not appear under Port

  • Try a USB cable that supports data; some cables provide power only.
  • Try another USB port.
  • Confirm the board's power LED turns on.
  • A compatible board may need a USB-interface driver.

Upload error

  • Confirm Arduino Uno is selected.
  • Confirm the correct port is selected.
  • Close other programs using the serial port.
  • Disconnect unnecessary wiring if any was previously attached.
  • Press reset and try uploading again.

Serial Monitor shows strange characters

The baud-rate selection must match Serial.begin(9600). Select 9600 baud.

Setup message appears when Serial Monitor opens

On a normal Uno setup, opening Serial Monitor can trigger an automatic reset. Therefore the program starts again and prints the setup message.

Built-in LED works differently on another board

LED_BUILTIN depends on the selected board definition. This lesson targets the Uno; other boards may use a different pin or active level.


16. Independent challenge

Modify the program so that it performs this repeating pattern:

  1. LED ON for 200 ms
  2. LED OFF for 200 ms
  3. LED ON for 200 ms
  4. LED OFF for 1000 ms

Print an appropriate message before every change.

Extra reasoning challenge

Draw a Sense–Process–Act diagram for one of these systems:

  • automatic hand dryer;
  • refrigerator temperature controller;
  • parking barrier;
  • plant-watering controller.

Identify at least one input, one decision and one output.


17. Knowledge check quiz

Question 1

Which description best defines a microcontroller?

A. A power supply for sensors
B. A small computer containing CPU, memory and peripherals on one chip
C. A programming language
D. A type of resistor

Question 2

Which ATmega328P memory normally stores temporary variables while the program runs?

A. Flash
B. EEPROM
C. SRAM
D. USB

Question 3

What is the main role of the Program Counter?

A. Measure analog voltage
B. Identify the next instruction
C. Supply power
D. Store user settings after power loss

Question 4

Which statement is correct?

A. The Arduino Uno board and ATmega328P are exactly the same object.
B. The Uno is a development board whose main application microcontroller is the ATmega328P.
C. The ATmega328P is only a USB connector.
D. The Uno cannot run without a computer after uploading.

Question 5

What is the normal CPU instruction cycle described in this lesson?

A. Store–print–delete
B. Input–internet–output
C. Fetch–decode–execute
D. Compile–charge–sleep

Question 6

Which peripheral converts an analog voltage into a number?

A. ADC
B. GPIO output driver
C. EEPROM
D. Program Counter

Question 7

At 16 MHz, the clock provides approximately how many cycles each second?

A. 16
B. 16,000
C. 1,600,000
D. 16,000,000

Question 8

Why can changing a peripheral control register immediately affect hardware?

A. Registers are comments in the source code.
B. Control-register bits are connected to hardware configuration logic.
C. Registers exist only on the computer.
D. A register is another name for a USB cable.

<details> <summary><strong>Show answers and explanations</strong></summary>
  1. B. A microcontroller integrates processing, memory and peripherals in one chip.
  2. C. SRAM holds working data and loses it when power is removed.
  3. B. The Program Counter tracks the next program instruction.
  4. B. The Uno is the supporting development board; the ATmega328P executes the application.
  5. C. The CPU repeatedly fetches, decodes and executes instructions.
  6. A. The Analog-to-Digital Converter produces a digital number from an analog input voltage.
  7. D. 16 MHz means 16 million cycles per second.
  8. B. Peripheral registers are part of the hardware interface; their bits configure or report real hardware behaviour.
</details>

18. Lesson summary

  • A microcontroller is a small computer on one chip.
  • An embedded system combines hardware and software for a dedicated purpose.
  • Many systems follow the pattern Sense → Process → Act.
  • The Arduino Uno is a development board; its ATmega328P executes the application.
  • The CPU executes instructions and the ALU performs arithmetic and logic operations.
  • Flash stores the program, SRAM holds temporary working data, and EEPROM stores selected persistent values.
  • A clock coordinates internal operations; the Uno normally operates the ATmega328P at 16 MHz.
  • Registers are small hardware storage locations used for CPU work, peripheral control and status.
  • The CPU repeatedly fetches, decodes and executes instructions.
  • Arduino functions provide a convenient layer above the ATmega328P registers.

Key terms

TermBeginner definition
MicrocontrollerSmall computer integrated into one chip
Embedded systemDedicated electronic system containing hardware and software
CPUUnit that executes instructions
ALUCPU section that performs arithmetic and logic
ClockRepeating timing signal that paces operations
FlashNon-volatile program memory
SRAMVolatile working memory
EEPROMNon-volatile memory for selected saved data
RegisterSmall hardware storage location used by CPU or peripherals
PeripheralSpecialised hardware block such as GPIO, ADC or timer
Program CounterRegister identifying the next instruction
BusInternal paths that transport data and control information
FirmwareSoftware stored in and executed by an embedded device
GPIOGeneral-purpose digital input/output hardware
ADCHardware that converts analog voltage to a digital value

STM32 transfer preview

An STM32 microcontroller has the same broad ideas:

  • CPU, clock and registers;
  • Flash and SRAM;
  • GPIO, ADC, timers and communication peripherals;
  • fetch–decode–execute operation.

The detailed architecture differs. Common STM32 devices use a 32-bit Arm Cortex-M CPU, different register names, more complex clock controls and an interrupt controller called NVIC. Once you understand the universal blocks in this lesson, you have the foundation for learning STM32 later.

Next lesson

Lesson 2 — Arduino Uno and ATmega328P Architecture
Next, we will map Arduino headers to the microcontroller pins, inspect memory organisation, study reset/startup and examine how the board supports the chip.


Instructor/source notes

Technical values in this lesson are based on the Microchip ATmega48A/PA/88A/PA/168A/PA/328/P family documentation and Arduino Uno Rev3 documentation. Simplified diagrams are original teaching figures for EMBEDLIX and are not scale drawings.

  • Microchip, ATmega48A/PA/88A/PA/168A/PA/328/P Data Sheet.
  • Arduino, UNO R3 hardware documentation.
Course overview