CSE 324 / 325 · ATmega328

AVR Embedded
Systems · Study Guide

Socratic walkthroughs & practice quizzes for the full course
قبل ما تبدا سمي الله و صلي عالنبي

Welcome 👋

This interactive study guide is designed to help you master AVR Embedded Systems and ATmega328P architecture. Navigate through different learning styles using the modes below:

  • 📖 Tutorial Mode: Walk through guided Socratic explanations, interactive code snippets, and review core lecture concepts step-by-step.
  • 🔧 Interactive Coding: Practice writing and arranging AVR Assembly and C code with real-time check feedback.
  • ⚡ Practice Quiz: Challenge yourself with exam-style multiple-choice questions, detailed explanations, and track your mistakes.
  • ⚡🔧 Blitz Coding: Test your skills with customized, randomized coding tasks across multiple topics to build speed and accuracy.

💡 Pro-Tip: Press Ctrl+K (or click the search 🔍 icon next to Home) to search for anything instantly across tutorials, quizzes, and coding tasks. You can also view reference answers using the new 🔓 Solution button during coding tasks!

📖
Tutorial Mode
Learn with structured walkthroughs and interactive step-by-step hints
0 / 0
🔧
Interactive Coding
Practice writing code with fill-in, line builder, and scratch coding
0 / 0
Practice Quiz
Test your understanding with exam-style MCQs and track mistakes
⚡🔧
Blitz Coding
Practice randomized coding tasks across multiple topics with custom counts
🧪
Tutorial Coding — Post-Midterm Focus
Guided write-the-whole-program walkthroughs + every existing coding task for the five exam-2 lectures.
⏱️ Timer ⚡ Interrupts 📡 UART 📊 ADC 📨 SPI
Sheet questions only Restrict the pool to questions that came directly from the practice sheets
10
15
20
All
of 0
Practice modeShow the correct answer & explanation after each question
Shuffle questionsRandomize the order each attempt
Sheet questions only Restrict the pool to coding tasks pulled from the practice sheets
5
10
15
All
of 0
Mix question stylesInterleave fill, line builder, and scratch coding questions
Shuffle questionsRandomize the order each attempt
📋 Formula Sheet
Check formulas, truth tables, and registers anytime!
TUTORIAL MODEChoose a topic
Which topic do you want to walk through?
🧠
AVR Architecture (Lecture 1)
Microcontroller vs microprocessor · AVR families · part numbers · internal block diagram
⚙️
Assembly Basics (Lecture 2)
LDI/ADD/SUB · R0-R31 · SREG flags · LDS/STS · .EQU/.ORG · RISC + Harvard · machine code
🔀
Jump & Call (Lecture 3)
RJMP/JMP/IJMP · conditional branches · stack · RCALL/CALL/RET · time delays
💡
GPIO & Bit Fiddling (Lecture 4)
DDR/PORT/PIN · bitwise set/clear/toggle · pull-up resistors · reading inputs · debouncing
⏱️
Timer / Counter (Lecture 5)
TCNT, TCCR, TIFR, OCR · Normal & CTC modes · prescaler · counter mode · delay calculation
Interrupts (Lecture 6)
Polling vs ISR · vector table · INT0/INT1 · Timer interrupts · pin change · context saving
📡
UART / Serial (Lecture 7)
Serial vs parallel · simplex/duplex · baud rate & UBRR · UCSRA/B/C · UDR · TX/RX patterns
📊
ADC (Lecture 8)
Analog→digital · step size · ADMUX/ADCSRA · Vref · prescaler · LM35 sensor · reading ADCL/ADCH
🔧
PWM & DC Motor (Lecture 9 — Not in Exam)
Duty cycle · Fast vs Phase-Correct PWM · COM bits · OCR formulas · L298 H-bridge · speed control
📨
SPI Protocol (Lecture 10)
Master/slave shift-register exchange · MOSI/MISO/SCK/SS · SPCR/SPSR/SPDR · CPOL/CPHA · multi-slave bus
📝
Tutorial Quizzes (past quizzes)
The actual quizzes you took in the tutorial sessions — Quiz 1 models A, C, D, E
LINKSMore Practice
Need more coding challenges?
1 / 1
1 / 1
0 ✓
0 ✗
Q1
Your Result
0/0
0%
0
Correct
0
Wrong
0
Skipped
Review
Paste the copied review into ChatGPT, Claude, or any LLM for a deeper walkthrough of the questions you missed.
CODING MODEPick a topic
Which topic do you want to practice writing code for?
1 / 1
FILL
25:00
Start focus timer
🍅 Focus Timer
Pomodoro / break / stopwatch — keeps counting across pages and refreshes.

🍅 Focus Timer

25:00
Focus Session
Sound chime Play a gentle tone when the timer ends

⏳ Final Exam Countdown

We are counting down till the final exam:
00d 00h 00m 00s
0 days left

📋 Exam Reference Sheet

AVR Architecture & Memories (ATmega328P)

Harvard Architecture: Separate program bus (Flash) and data bus (SRAM/Registers). Allows simultaneous instruction fetch and data access.

Memory Sizes:

  • Flash (Program Memory): 32 KB (16K x 16-bit instructions, 2-byte/4-byte size)
  • SRAM (Data Memory): 2 KB (General Purpose R0-R31, I/O registers, internal SRAM)
  • EEPROM (Non-volatile): 1 KB (Data storage surviving reset/power loss)

Registers: 32 general-purpose registers (R0-R31). Only R16-R31 support immediate loading (LDI). X=R27:R26, Y=R29:R28, Z=R31:R30 are 16-bit pointer registers.

📋 MCU Control Instructions (from Exam Sheet)
MnemonicOperandsDescriptionOperationFlags Affected
NOPNoneNo OperationNoneNone
SLEEPNoneSleep / Enter Power-down mode(See sleep description)None
WDRNoneWatchdog Reset(See watchdog description)None
BREAKNoneBreak / On-chip debug supportFor On-chip debug onlyNone

AVR Assembly Basics

General syntax: INSTRUCTION Destination, Source

Core Instructions:

  • LDI Rd, K: Load constant K (0-255) into Rd (R16-R31).
  • LDS Rd, k: Load byte from SRAM address k (16-bit address).
  • STS k, Rr: Store register Rr byte to SRAM address k.
  • IN Rd, A: Read byte from I/O register A (address 0-63).
  • OUT A, Rr: Write register Rr to I/O register A (address 0-63).
  • MOV Rd, Rr: Copy register Rr to Rd.
  • ADD Rd, Rr: Add Rr to Rd (updates SREG flags: C, Z, N, V, H).
  • SUB Rd, Rr: Subtract Rr from Rd (updates flags).
  • INC Rd / DEC Rd: Increment / Decrement register Rd.
  • CP Rd, Rr: Compare Rd with Rr (performs subtraction, updates flags, doesn't write back Rd).

SREG (Status Register) Flags: I T H S V N Z C (C=Carry, Z=Zero, N=Negative, V=Overflow, S=Sign, H=Half-Carry, I=Global Interrupt Enable).

📋 Data Transfer Instructions (from Exam Sheet)
MnemonicOperandsDescriptionOperationFlags
MOVRd, RrCopy RegisterRd ← RrNone
MOVWRd, RrCopy Register WordRd+1:Rd ← Rr+1:RrNone
LDIRd, KLoad Immediate (R16-R31)Rd ← KNone
LDSRd, kLoad Direct from SRAMRd ← (k)None
STSk, RrStore Direct to SRAM(k) ← RrNone
LDRd, X / X+ / -XLoad Indirect using X PointerRd ← (X), post-inc or pre-decNone
LDRd, Y / Y+ / -YLoad Indirect using Y PointerRd ← (Y), post-inc or pre-decNone
LDDRd, Y+qLoad Indirect with DisplacementRd ← (Y + q)None
LDRd, Z / Z+ / -ZLoad Indirect using Z PointerRd ← (Z), post-inc or pre-decNone
LDDRd, Z+qLoad Indirect with DisplacementRd ← (Z + q)None
STX / X+ / -X, RrStore Indirect using X Pointer(X) ← Rr, post-inc or pre-decNone
STY / Y+ / -Y, RrStore Indirect using Y Pointer(Y) ← Rr, post-inc or pre-decNone
STDY+q, RrStore Indirect with Displacement(Y + q) ← RrNone
STZ / Z+ / -Z, RrStore Indirect using Z Pointer(Z) ← Rr, post-inc or pre-decNone
STDZ+q, RrStore Indirect with Displacement(Z + q) ← RrNone
LPMNone / Rd, Z / Rd, Z+Load Program MemoryRd ← (Z), post-inc optionNone
SPMNoneStore Program Memory(Z) ← R1:R0None
INRd, PIn Port / Read I/O PortRd ← PNone
OUTP, RrOut Port / Write I/O PortP ← RrNone
PUSHRrPush Register on StackStack ← RrNone
POPRdPop Register from StackRd ← StackNone
📋 Arithmetic and Logic Instructions (from Exam Sheet)
MnemonicOperandsDescriptionOperationFlags
ADDRd, RrAdd registersRd ← Rd + RrZ, C, N, V, H
ADCRd, RrAdd with Carry registersRd ← Rd + Rr + CZ, C, N, V, H
ADIWRdl, KAdd Immediate to WordRdh:Rdl ← Rdh:Rdl + KZ, C, N, V, S
SUBRd, RrSubtract registersRd ← Rd - RrZ, C, N, V, H
SUBIRd, KSubtract Immediate from registerRd ← Rd - KZ, C, N, V, H
SBCRd, RrSubtract with Carry registersRd ← Rd - Rr - CZ, C, N, V, H
SBCIRd, KSubtract with Carry ImmediateRd ← Rd - K - CZ, C, N, V, H
SBIWRdl, KSubtract Immediate from WordRdh:Rdl ← Rdh:Rdl - KZ, C, N, V, S
ANDRd, RrLogical AND registersRd ← Rd • RrZ, N, V
ANDIRd, KLogical AND register with ImmediateRd ← Rd • KZ, N, V
ORRd, RrLogical OR registersRd ← Rd v RrZ, N, V
ORIRd, KLogical OR register with ImmediateRd ← Rd v KZ, N, V
EORRd, RrExclusive OR registersRd ← Rd ⊕ RrZ, N, V
COMRdOne's Complement (Bitwise NOT)Rd ← 0xFF - RdZ, C, N, V
NEGRdTwo's Complement (Negate)Rd ← 0x00 - RdZ, C, N, V, H
SBRRd, KSet Bits in RegisterRd ← Rd v KZ, N, V
CBRRd, KClear Bits in RegisterRd ← Rd • (0xFF - K)Z, N, V
INCRdIncrementRd ← Rd + 1Z, N, V
DECRdDecrementRd ← Rd - 1Z, N, V
TSTRdTest for Zero or MinusRd ← Rd • RdZ, N, V
CLRRdClear RegisterRd ← 0x00Z, N, V
SERRdSet Register (All ones)Rd ← 0xFFNone
MULRd, RrMultiply UnsignedR1:R0 ← Rd × RrZ, C
MULSRd, RrMultiply SignedR1:R0 ← Rd × RrZ, C
MULSURd, RrMultiply Signed with UnsignedR1:R0 ← Rd × RrZ, C

Jump & Call Instructions (Program Flow)

Unconditional Jumps:

  • RJMP k: Relative jump (offset ±2K instructions, 2-byte instruction, 2 cycles).
  • JMP k: Absolute jump to 22-bit address (4-byte instruction, 3 cycles).
  • IJMP: Indirect jump (jumps to the address stored in the Z register R31:R30).

Subroutine Calls:

  • RCALL k / CALL k: Pushes Program Counter (PC) (2 bytes) onto Stack, decrements SP by 2, then jumps.
  • RET: Return from subroutine. Pops 2 bytes from Stack into PC, increments SP by 2.
  • RETI: Return from Interrupt Service Routine. Same as RET but also sets SREG global interrupt bit (I = 1) automatically.

Stack Pointer Initialization (RAMEND = 0x08FF):

LDI R16, HIGH(RAMEND) OUT SPH, R16 LDI R16, LOW(RAMEND) OUT SPL, R16

Conditional Branches: BREQ k (branch if Z=1), BRNE k (branch if Z=0), BRCS k (branch if C=1), BRCC k (branch if C=0). Relative offset range: -64 to +63 instructions.

📋 Branch & Jump Instructions (from Exam Sheet)
MnemonicOperandsDescriptionOperationFlags
RJMPkRelative JumpPC ← PC + k + 1None
JMPkDirect Absolute JumpPC ← kNone
IJMPNoneIndirect Jump to (Z)PC ← Z (R31:R30)None
RCALLkRelative Subroutine CallPC ← PC + k + 1, push StackNone
CALLkDirect Absolute Subroutine CallPC ← k, push StackNone
ICALLNoneIndirect Call to (Z)PC ← Z, push StackNone
RETNoneSubroutine ReturnPC ← StackNone
RETINoneInterrupt ReturnPC ← Stack, SREG I ← 1I
CPSERd, RrCompare, Skip if Equalif (Rd == Rr) PC ← PC + 2 or 3None
CPRd, RrCompareRd - RrZ, N, V, C, H
CPCRd, RrCompare with CarryRd - Rr - CZ, N, V, C, H
CPIRd, KCompare Register with ImmediateRd - KZ, N, V, C, H
SBRCRr, bSkip if Bit in Register is Clearedif (Rr(b)==0) PC ← PC + 2 or 3None
SBRSRr, bSkip if Bit in Register is Setif (Rr(b)==1) PC ← PC + 2 or 3None
SBICP, bSkip if Bit in I/O Reg is Clearedif (P(b)==0) PC ← PC + 2 or 3None
SBISP, bSkip if Bit in I/O Reg is Setif (P(b)==1) PC ← PC + 2 or 3None
BRBSs, kBranch if Status Flag Setif (SREG(s)==1) PC ← PC+k+1None
BRBCs, kBranch if Status Flag Clearedif (SREG(s)==0) PC ← PC+k+1None
BREQkBranch if Equalif (Z == 1) PC ← PC + k + 1None
BRNEkBranch if Not Equalif (Z == 0) PC ← PC + k + 1None
BRCS / BRLOkBranch if Carry Set / Lowerif (C == 1) PC ← PC + k + 1None
BRCC / BRSHkBranch if Carry Clear / Same or Higherif (C == 0) PC ← PC + k + 1None
BRMIkBranch if Minus (Negative)if (N == 1) PC ← PC + k + 1None
BRPLkBranch if Plus (Positive)if (N == 0) PC ← PC + k + 1None
BRGEkBranch if Greater or Equal (Signed)if (N ⊕ V == 0) PC ← PC + k + 1None
BRLTkBranch if Less Than Zero (Signed)if (N ⊕ V == 1) PC ← PC + k + 1None
BRHSkBranch if Half Carry Setif (H == 1) PC ← PC + k + 1None
BRHCkBranch if Half Carry Clearedif (H == 0) PC ← PC + k + 1None

GPIO & Bit Fiddling (ATmega328P Port Registers)

Each port (B, C, D) has three registers: DDRx (Direction), PORTx (Output / Pull-up), and PINx (Input Pin Value - Read Only).

DDRx BitPORTx BitPin ConfigDescription
0 (Input)0Input, High-ZPin is floating (high impedance). Input reading is volatile.
0 (Input)1Input, Pull-upInternal 20K-50K pull-up resistor enabled. Pin idles HIGH.
1 (Output)0Output, LOWPin is driven to GND (0V). Can sink current.
1 (Output)1Output, HIGHPin is driven to VCC (5V). Can source current.

Bitwise Trinity in C:

  • Set bit: PORTB |= (1 << 5);
  • Clear bit: PORTB &= ~(1 << 5);
  • Toggle bit: PORTB ^= (1 << 5);
  • Read pin: if ((PINB & (1 << 3)) == 0) { ... }

Directives in Assembly: SBI ioreg, bit (Set bit in I/O reg), CBI ioreg, bit (Clear bit), SBIS ioreg, bit (Skip next instruction if I/O bit is set), SBIC ioreg, bit (Skip if clear).

📋 Bit and Bit-Test Instructions (from Exam Sheet)
MnemonicOperandsDescriptionOperationFlags
SBIP, bSet Bit in I/O RegisterI/O(P, b) ← 1None
CBIP, bClear Bit in I/O RegisterI/O(P, b) ← 0None
LSLRdLogical Shift LeftRd(n+1) ← Rd(n), Rd(0) ← 0Z, C, N, V
LSRRdLogical Shift RightRd(n) ← Rd(n+1), Rd(7) ← 0Z, C, N, V
ROLRdRotate Left through CarryRd(0) ← C, Rd(n+1) ← Rd(n), C ← Rd(7)Z, C, N, V
RORRdRotate Right through CarryRd(7) ← C, Rd(n) ← Rd(n+1), C ← Rd(0)Z, C, N, V
ASRRdArithmetic Shift RightRd(n) ← Rd(n+1), Rd(7) remainsZ, C, N, V
SWAPRdSwap NibblesRd(3..0) ↔ Rd(7..4)None
BSETsFlag Set in SREGSREG(s) ← 1SREG(s)
BCLRsFlag Clear in SREGSREG(s) ← 0SREG(s)
BSTRr, bStore Bit in Register to T FlagT ← Rr(b)T
BLDRd, bLoad Bit from T Flag to RegisterRd(b) ← TNone
SEC / CLCNoneSet / Clear Carry FlagC ← 1 / 0C
SEZ / CLZNoneSet / Clear Zero FlagZ ← 1 / 0Z
SEI / CLINoneSet / Clear Global InterruptI ← 1 / 0I

Timer / Counter (Truth Tables & Calculations)

Calculations:

  • Delay tick:
  • Ttick =
    Nprescaler
    fCPU
  • Preload Value (Normal Mode):
  • Preload = 2n
    Delay × fCPU
    Nprescaler
    (where n = 8 or 16 bits)
  • Compare Value (CTC Mode):
  • OCR =
    Delay × fCPU
    Nprescaler
    − 1

CTC & Normal Mode Selection Cheat Sheet:

  • Timer 0 / Timer 2 (8-bit) Normal Mode: TCCR0A = 0x00; (WGM02:00 = 000)
  • Timer 0 / Timer 2 (8-bit) CTC Mode: TCCR0A = (1<<WGM01); (WGM02:00 = 010)
  • Timer 1 (16-bit) Normal Mode: TCCR1A = 0x00; TCCR1B = 0x00; (WGM13:10 = 0000)
  • Timer 1 (16-bit) CTC Mode (TOP=OCR1A): TCCR1A = 0x00; TCCR1B = (1<<WGM12); (WGM13:10 = 0100)

WGM (Waveform Generation Mode) Truth Tables:

Timer 0 and Timer 2 (8-bit):

ModeWGM02WGM01WGM00Mode DescriptionTOPTOV Flag Set on
0000Normal (Upcounting)0xFFMAX (0xFF)
2010CTC (Clear Timer on Compare Match)OCR0AMAX (0xFF)
3011Fast PWM0xFFMAX (0xFF)
7111Fast PWMOCR0ATOP

Timer 1 (16-bit):

ModeWGM13WGM12WGM11WGM10Mode DescriptionTOPTOV Flag Set on
00000Normal (Upcounting)0xFFFFMAX (0xFFFF)
40100CTC (Clear Timer on Compare Match)OCR1AMAX (0xFFFF)
141110Fast PWMICR1TOP
151111Fast PWMOCR1ATOP

Clock Source / Prescaler Selector (CS02:CS00 for Timer 0 & 1):

CSn2CSn1CSn0Prescaler / Clock Source Selection
000No clock source (Timer/Counter stopped)
001clk_I/O (No prescaling)
010clk_I/O / 8
011clk_I/O / 64
100clk_I/O / 256
101clk_I/O / 1024
110External clock on Tn pin (Falling Edge)
111External clock on Tn pin (Rising Edge)

Interrupts (Vectors & Registers)

Registers:

  • SREG (bit 7 - I): Global Interrupt Enable. Set by sei(), cleared by cli().
  • EIMSK: External Interrupt Mask Register (bit 0 = INT0 enable, bit 1 = INT1 enable).
  • EICRA: External Interrupt Control Register A. Configures trigger edges:
ISCn1ISCn0Trigger Mode Description
00Low level of INTn pin generates interrupt request
01Any logical change on INTn pin generates interrupt request
10Falling edge of INTn pin generates interrupt request
11Rising edge of INTn pin generates interrupt request

Selected Vector Table Addresses (in Flash):

  • Reset: 0x0000
  • INT0: 0x0002
  • INT1: 0x0004
  • TIMER1 COMPA: 0x0016
  • TIMER1 OVF: 0x001A
  • TIMER0 OVF: 0x0020

UART / Serial Communication (USART0)

Baud Rate Divisor Formulas (Async Normal Mode, U2X0 = 0):

UBRR0 =
fCPU
16 × Baud
− 1
Baud =
fCPU
16 × (UBRR0 + 1)

Baud Rate Divisor Formulas (Async Double Speed Mode, U2X0 = 1):

UBRR0 =
fCPU
8 × Baud
− 1

Core Registers:

  • UDR0: USART Data Register (Read = RX buffer, Write = TX buffer).
  • UCSR0A: Status register. Bits: RXC0 (Receive Complete flag), TXC0 (Transmit Complete flag), UDRE0 (USART Data Register Empty flag - 1 means ready to accept new byte).
  • UCSR0B: Control register B. Bits: RXCIE0 (RX Complete Interrupt Enable), RXEN0 (Receiver Enable), TXEN0 (Transmitter Enable), UCSZ02 (Character Size bit 2).
  • UCSR0C: Control register C. Bits: UMSEL01:UMSEL00 (00 = Async, 01 = Sync), UPM01:UPM00 (Parity: 00=None, 10=Even, 11=Odd), USBS0 (Stop bits: 0=1-bit, 1=2-bit), UCSZ01:UCSZ00 (Character size: 11 = 8-bit).

ADC (Analog-to-Digital Converter)

Voltage to Digital Conversion Formula:

ADC Output =
Vin × 1024
Vref
Step Size =
Vref
1024

Core Registers:

  • ADMUX: Channel and Reference Selection.
    • REFS1:REFS0: 00 = AREF pin, 01 = AVCC with capacitor at AREF, 11 = Internal 1.1V ref.
    • ADLAR: Left Adjust Result. (0 = Right adjusted to ADCL/ADCH, 1 = Left adjusted).
    • MUX3:MUX0: Analog Channel Select (0000 = ADC0, 0001 = ADC1, ..., 0101 = ADC5).
  • ADCSRA: Control and Status Register A.
    • ADEN: ADC Enable. Must be 1 to use ADC.
    • ADSC: ADC Start Conversion. Write 1 to start conversion.
    • ADIF: ADC Interrupt Flag. Becomes 1 when conversion is complete. Clear by writing 1.
    • ADIE: ADC Interrupt Enable.
    • ADPS2:ADPS0: Prescaler Select bits. Divides system clock to ADC clock (must be between 50kHz and 200kHz for max accuracy). 111 = clk/128, 110 = clk/64.

PWM & DC Motor Control (Not in Exam)

PWM Frequency Formulas:

fFast PWM =
fCPU
N × 256
fPhase Correct =
fCPU
N × 510

Duty Cycle Calculations:

Fast PWM Duty =
OCR + 1
256
× 100%
Phase Correct Duty =
OCR
255
× 100%

Compare Output Mode in Fast PWM (COM0A1:COM0A0):

COM0A1COM0A0Compare Output Mode Description
00Normal port operation, OC0A disconnected
10Clear OC0A on Compare Match, set OC0A at BOTTOM (non-inverting mode)
11Set OC0A on Compare Match, clear OC0A at BOTTOM (inverting mode)