Microcontrollers cover
Interactive book · Semester 4

Microcontrollers

Step through 8051 code, load timers, send serial frames and fire interrupts in your browser

Fourteen chapters, 11 interactives, few words. Every chapter is mapped to the Anna University, VTU, SPPU, Mumbai University and KTU units it covers: the 8051 from its memory map and instruction set to timers, the serial port, interrupts and interfacing, then the PIC18, serial buses, ARM, RTOS scheduling and IoT.

  • AUET3491Embedded Systems and IoT Design
  • VTUBEC405A8051 Microcontroller
  • SPPU304184Microcontroller
  • MUECC402Microcontrollers
  • KTUPBECT404Microcontrollers

By Skill-Lync · Updated 16 Nov 2026 · 14 chapters · 11 interactives · free, no sign-up

Chapter 1

Microprocessors, microcontrollers and memory

Which syllabus covers thisAU ET3491 Unit IVTU BEC405A Module 1SPPU 304184 Unit IMU ECC402 Modules 1 and 2, 3.1KTU PBECT404 Module 1

What is the difference between a microprocessor and a microcontroller?

A microprocessor is only the CPU: memory, timers and I/O sit on other chips, which suits a PC that needs gigabytes of RAM. A microcontroller puts the CPU, program memory, RAM, timers, a serial port and I/O pins on one chip, so a washing machine or a car window needs one cheap part. The 8051 (Intel, 1980) has 4 KB of ROM, 128 bytes of RAM, 32 I/O pins, two 16-bit timers, one serial port and five interrupt sources on a 40-pin chip.

Harvard or von Neumann architecture?

Von Neumann uses one memory and one bus for both program and data, so an instruction fetch and a data access take turns. Harvard keeps them separate, so the next instruction can be fetched while data moves. The 8051 has separate program (code) and data address spaces, 64 KB each; the PIC18 and the ARM Cortex-M are Harvard too, the ARM7 is von Neumann.

RISC or CISC?

CISC (complex instruction set) offers many instructions of different lengths and cycle counts, some doing a lot of work each (the 8051 has 111 instructions, 1 to 3 bytes, 1 to 4 machine cycles). RISC (reduced instruction set) uses few, simple, same-length instructions that finish in one cycle and pipeline well: PIC, AVR and ARM are RISC.

What do the address, data and control buses do?

The address bus says where (16 lines reach 2¹⁶ = 64 KB), the data bus carries what (8 lines on an 8-bit chip) and the control bus says when and which way: read, write, ALE, PSEN. One fetch is: put the PC on the address bus, read the opcode on the data bus, increment the PC, decode and execute.

Which memories does an embedded system use?

Program code lives in non-volatile memory: mask ROM, OTP, EPROM (UV-erased), EEPROM and, today, flash. Variables live in RAM: SRAM (fast, no refresh, used on chip) or DRAM (dense, needs refresh). Bigger processors add a cache, a small fast copy of recently used memory, and virtual memory, where an MMU translates addresses through segments or pages so each program sees its own address space.

Predict, then check

An 8051 runs from an 11.0592 MHz crystal. How long does MUL AB (4 machine cycles) take?

Worked examples

Machine cycle and instruction time · 8051, 11.0592 MHz crystal, MUL AB takes 4 machine cycles
  1. Machine cycle = 12 / 11.0592 MHz = 1.085 µs
  2. MUL AB = 4 × 1.085 = 4.34 µs
  3. A 1-cycle instruction such as MOV A,R0 takes 1.085 µs

Answer: 4.34 µs

Address lines for a memory · A 4 KB ROM and the full 64 KB 8051 address space
  1. 4 KB = 4096 = 2¹² locations, so 12 address lines (A0 to A11)
  2. 64 KB = 65,536 = 2¹⁶, so 16 lines (A0 to A15)
  3. The upper 4 lines can then select one of 16 such 4 KB blocks

Answer: 12 lines for 4 KB, 16 lines for 64 KB

Building 32 KB from 8 KB chips · 8K × 8 RAM chips, 32 KB needed at 0000H to 7FFFH
  1. 32 / 8 = 4 chips
  2. Each 8K chip needs 13 address lines (2¹³ = 8192): A0 to A12
  3. A13 and A14 go to a 2-to-4 decoder that picks the chip; A15 = 0 enables the decoder

Answer: 4 chips; A13 A14 decoded, A15 = 0

Chapter 2

8051 architecture and memory organisation

Which syllabus covers thisAU ET3491 Unit IVTU BEC405A Module 1SPPU 304184 Units I and IIMU ECC402 Modules 3.2 to 3.5KTU PBECT404 Module 1

How is the 8051's internal RAM organised?

128 bytes, 00H to 7FH. 00H to 1FH are four register banks of eight registers R0 to R7; the bank in use is picked by RS1 RS0 in the PSW. 20H to 2FH are bit-addressable: their 128 bits have bit addresses 00H to 7FH. 30H to 7FH is the scratch pad for variables and the stack. Click a bank and a bit address to see where they land.

8051 internal RAM map: register banks, bit-addressable area and scratch pad: interactive loads as you scroll

What is in the PSW?

The Program Status Word holds the flags: CY (carry, bit 7), AC (auxiliary carry out of bit 3, for BCD), F0 (a user flag), RS1 and RS0 (register bank select), OV (signed overflow) and P (parity: 1 when A holds an odd number of 1s). Arithmetic sets CY, AC and OV; P follows A after every instruction.

What are SFRs?

Special Function Registers sit at direct addresses 80H to FFH: A (E0H), B (F0H), PSW (D0H), SP (81H), DPTR (DPH 83H, DPL 82H), the ports P0 to P3 (80H, 90H, A0H, B0H), and the timer, serial and interrupt registers. Those whose address ends in 0 or 8 are bit-addressable, so SETB P1.7 works (bit address 97H). After reset: PC = 0000H, SP = 07H, A = 00H, PSW = 00H and every port = FFH.

What do the four ports and the special pins do?

P0 (open drain, needs pull-ups) doubles as the multiplexed low address and data bus AD0 to AD7; P2 gives the high address A8 to A15; P1 is plain I/O; P3 pins also carry RXD, TXD, INT0, INT1, T0, T1, WR and RD. ALE latches the low address byte into a 74LS373 during external access; PSEN reads external code; EA tied high runs the on-chip ROM. A port pin must be written 1 before it is used as an input.

How is external memory connected?

Code and data each have a 64 KB external space. The 8051 puts the low address on P0 and pulses ALE so a latch holds it, then uses P0 for data; P2 holds the high address. Code is read with PSEN (MOVC), external data with RD and WR (MOVX). ALE runs at one sixth of the crystal frequency when no MOVX is in progress.

Predict, then check

Your program uses register bank 1, and you never change SP. What happens on the first PUSH?

Worked examples

Register address in a bank · Bank 2 selected; where is R5, and what is the PSW?
  1. Bank 2 starts at 2 × 8 = 16 = 10H
  2. R5 = 10H + 5 = 15H
  3. RS1 RS0 = 1 0, which is PSW bits 4 and 3: PSW = 10H (other flags 0)

Answer: R5 is at 15H; PSW = 10H

Bit address to byte and bit · SETB 67H
  1. Bit addresses 00H to 7FH map into bytes 20H to 2FH, eight per byte
  2. 67H = 103; 103 ÷ 8 = 12 remainder 7
  3. Byte 20H + 12 = 2CH, bit 7

Answer: SETB 67H sets bit 7 of RAM byte 2CH

ALE frequency · 11.0592 MHz crystal, no MOVX running
  1. ALE pulses twice per machine cycle: f/6
  2. 11.0592 / 6 = 1.8432 MHz
  3. It can clock other logic, but stops during MOVX cycles

Answer: 1.8432 MHz

Chapter 3

Addressing modes and the instruction set

Which syllabus covers thisAU ET3491 Unit IVTU BEC405A Module 2SPPU 304184 Unit IMU ECC402 Modules 4.1 and 4.2KTU PBECT404 Module 2

What are the 8051's addressing modes?

Immediate (MOV A,#25H: the number itself), register (MOV A,R3), direct (MOV A,40H: RAM or SFR address), register indirect (MOV A,@R0: R0 holds the address; only R0 and R1 can do this), and indexed (MOVC A,@A+DPTR: read a table in code memory). Jumps use relative (SJMP, −128 to +127 bytes), absolute (AJMP/ACALL, within a 2 KB page) and long (LJMP/LCALL, anywhere in 64 KB) addresses.

Which instructions change the flags, and how?

ADD, ADDC and SUBB set CY (carry or borrow out of bit 7), AC (out of bit 3) and OV (the signed result is wrong: two positives give a negative, or two negatives a positive). INC, DEC, MOV and logic instructions leave CY alone. Step through the programs below and watch each flag change.

Step through 8051 assembly programs and watch registers and flags change: interactive loads as you scroll

How do MUL, DIV and DA work?

MUL AB multiplies A by B and leaves the 16-bit product in B (high) and A (low); OV = 1 if the product exceeds 255. DIV AB puts the quotient in A and the remainder in B (OV = 1 if B was 0). DA A corrects A after adding two packed-BCD numbers: add 6 to a nibble that went above 9 or produced a carry.

What do the logical and bit instructions do?

ANL, ORL and XRL work bit by bit (AND clears bits, OR sets them, XOR toggles them); CPL inverts, RL and RR rotate, RLC and RRC rotate through the carry, SWAP exchanges the nibbles. Bit instructions (SETB, CLR, CPL, MOV C,bit, JB, JNB, JBC) work on single bits, which is how a pin or a flag is tested in one instruction.

How do loops and decisions work?

DJNZ Rn,label decrements and jumps while not zero: the standard loop counter. CJNE compares two values and jumps if they differ; it also sets CY when the first is smaller, so a following JC or JNC tells less from greater. JZ and JNZ test A; JC and JNC test the carry. Relative jumps are measured from the address of the next instruction.

Predict, then check

A = 7FH. After ADD A,#01H, which flags are set?

Worked examples

Flags after an addition · MOV A,#38H then ADD A,#2FH
  1. 38H + 2FH = 67H, no carry out of bit 7: CY = 0
  2. Low nibbles 8 + F = 17 > 15: AC = 1
  3. Both operands and the result are positive: OV = 0
  4. 67H = 0110 0111 has five 1s (odd): P = 1

Answer: A = 67H, CY = 0, AC = 1, OV = 0, P = 1

BCD addition · A = 47H (BCD 47), ADD A,#25H, then DA A
  1. Binary sum 47H + 25H = 6CH
  2. Low nibble C > 9: add 06H, giving 72H
  3. High nibble 7 ≤ 9 and CY = 0: no further change

Answer: A = 72H, which is BCD 47 + 25 = 72

Subtract with borrow · CLR C, MOV A,#4CH, SUBB A,#6EH
  1. 4CH − 6EH = 76 − 110 = −34
  2. 8-bit result: 256 − 34 = 222 = DEH
  3. A borrow was needed: CY = 1 (the result is negative in 2's complement)

Answer: A = DEH, CY = 1

Relative jump target · SJMP at 0100H with relative byte F0H
  1. SJMP is 2 bytes, so the next instruction is at 0102H
  2. F0H as a signed byte is −16
  3. 0102H − 16 = 00F2H

Answer: Jumps to 00F2H

Chapter 4

Assembly programming: loops, stack, subroutines, delays

Which syllabus covers thisAU ET3491 Unit IVTU BEC405A Module 3SPPU 304184 Unit IMU ECC402 Modules 4.3 and 4.4KTU PBECT404 Module 3

What do assembler directives do?

They instruct the assembler and produce no machine code of their own: ORG sets the address where the next code goes, DB stores bytes (a table or a string), EQU names a constant, END ends the source. A cross assembler runs on a PC and produces the hex file for the 8051, which a programmer burns into flash.

How do the stack, PUSH, POP, CALL and RET work?

SP points at the top of the stack in internal RAM, and the stack grows upwards. PUSH increments SP and then writes; POP reads and then decrements. LCALL and ACALL push the return address (low byte first) and jump; RET pops it back into the PC. A subroutine that uses registers saves them with PUSH and restores them with POP in reverse order.

How long does a software delay take?

Count machine cycles: MOV takes 1, DJNZ, LCALL and RET take 2. In two nested DJNZ loops the inner DJNZ runs outer × inner times and takes almost all the time. Slide the counts and the crystal to get the delay you need.

Nested DJNZ software delay: machine cycles and time: interactive loads as you scroll

Which programs do the exams ask for?

Add N bytes (keep the carries in a second register), find the largest or smallest of N numbers (CJNE plus JC/JNC), move a block of bytes (two pointers, one counter), factorial of a small number (MUL AB in a loop), count 1s in a byte (RLC through the carry), and a delay subroutine. All of them are a pointer, a counter, a DJNZ loop and one decision; the Sum and Largest programs in chapter 3 run two of them step by step.

Predict, then check

In a two-loop DJNZ delay, you double the inner count. Roughly what happens to the delay?

Worked examples

Nested delay loop · R2 = 200, R3 = 250, 11.0592 MHz, called with LCALL
  1. LCALL 2 + MOV R2 1 + RET 2 = 5 cycles
  2. Each outer pass: MOV R3 (1) + 250 × DJNZ (2) + DJNZ R2 (2) = 503
  3. Total = 5 + 200 × 503 = 100,605 cycles
  4. × 1.0851 µs = 109.16 ms

Answer: 100,605 machine cycles ≈ 109.16 ms

Sum of five bytes · 7DH, EBH, C5H, 5BH, 30H at 40H to 44H
  1. 7D + EB + C5 + 5B + 30 = 125 + 235 + 197 + 91 + 48 = 696
  2. 696 = 2B8H
  3. A keeps the low byte B8H; R7 counts the two carries out of bit 7 (JNC skips INC R7)

Answer: A = B8H, R7 = 02H (sum 02B8H)

Factorial in 8 bits · 5! with MUL AB, result must fit in one byte
  1. 1 × 2 × 3 × 4 × 5 = 120
  2. 120 = 78H, below FFH, so B = 0 after every MUL
  3. 6! = 720 would not fit (OV = 1)

Answer: 5! = 78H; 5 is the largest n whose factorial fits in 8 bits

Chapter 5

Programming the 8051 in embedded C

Which syllabus covers thisAU ET3491 Unit IVTU BEC405A Modules 4 and 5 (C programs)SPPU 304184 Units I and IIMU ECC402 Module 4.4KTU PBECT404 Module 3

Why write 8051 programs in C?

C is quicker to write and read, easier to port to another microcontroller, and comes with libraries, while assembly gives the smallest, most predictable code. Most products are written in C with the time-critical parts in assembly. The Keil C51 compiler adds 8051 types to standard C: sfr (an SFR byte), sbit (a single SFR bit) and bit (a bit in RAM 20H to 2FH).

Which data types should you use?

Use unsigned char (0 to 255) wherever it will do: the 8051 is an 8-bit machine and an int (16 bits) costs several instructions per operation. signed char runs −128 to 127, unsigned int 0 to 65,535. Declare a pin once, for example sbit LED = P1^0; and then write LED = 1; or LED = ~LED;.

How do you change one pin without touching the others?

Read-modify-write with a mask: P1 |= 0x08 sets bit 3, P1 &= ~0x08 (mask F7H) clears it, P1 ^= 0x08 toggles it, and (P1 & 0x08) tests it. Shifts build masks: 1 << n is bit n. On the 8051, sbit does the same in one bit instruction.

How accurate is a delay loop in C?

Not very: the time of for (i = 0; i < 1275; i++); depends on the compiler, its optimisation level and the data types, so it must be measured in the simulator or on an oscilloscope. For exact times, use a timer (chapter 6).

What conversions come up in C programs?

Packed BCD to ASCII (split the nibbles with & 0x0F and >> 4, then add 0x30), binary to decimal digits (repeat % 10 and / 10), ASCII to packed BCD, and checksums: add all bytes, drop the carries, and send the 2's complement so that the receiver's sum comes out 00H.

Predict, then check

P1 = 0xF0. What is P1 after P1 ^= 0x18; ?

Worked examples

Set, clear and toggle bit 3 · P1 = 0xA5 (1010 0101)
  1. P1 | 0x08 = 1010 1101 = ADH (bit 3 set)
  2. P1 & 0xF7 = 1010 0101 = A5H (bit 3 already 0)
  3. P1 ^ 0x08 = 1010 1101 = ADH

Answer: |= sets, &= ~ clears, ^= toggles; only bit 3 can change

Binary to ASCII digits · x = 0xFD (253) to send over the serial port
  1. 253 % 10 = 3, 253 / 10 = 25
  2. 25 % 10 = 5, 25 / 10 = 2
  3. Add 0x30 to each digit: 32H, 35H, 33H

Answer: '2' '5' '3' = 32H 35H 33H

Checksum byte · Data 25H, 62H, 3FH, 52H
  1. 25H + 62H + 3FH + 52H = 118H
  2. Drop the carry: 18H
  3. 2's complement of 18H = E8H
  4. Check: 18H + E8H = 100H, low byte 00H

Answer: Checksum = E8H

Chapter 6

Timers and counters

Which syllabus covers thisAU ET3491 Unit IVTU BEC405A Module 4SPPU 304184 Unit IMU ECC402 Modules 3.6 and 4.4KTU PBECT404 Module 4

How are Timer 0 and Timer 1 set up?

Each is a 16-bit register pair (TH0/TL0, TH1/TL1) that counts up. TMOD sets both: the high nibble is Timer 1, the low nibble Timer 0, each GATE, C/T (0 = timer, 1 = counter) and M1 M0 (the mode). In TCON, TR0/TR1 start and stop the timers and TF0/TF1 go to 1 when they overflow.

What are the four timer modes?

Mode 0: 13-bit (8,192 counts). Mode 1: 16-bit (65,536 counts); the program reloads TH and TL after each overflow. Mode 2: 8-bit auto-reload: TL counts, and TH holds the value copied back in at overflow, which suits baud rates and steady square waves. Mode 3 splits Timer 0 into two 8-bit timers.

What value do you load for a given delay?

In timer mode the count goes up once per machine cycle (f/12). For a delay t, count N = t × f / 12 cycles, then load (maximum − N), so it overflows after exactly N counts. Pick a delay and a mode below to get TH0, TL0 and TMOD.

8051 Timer 0 reload values for a delay, in modes 0, 1 and 2: interactive loads as you scroll

How do you make a square wave on a pin?

Load the timer for half the period, start it, wait for TF, stop it, clear TF, complement the pin (CPL P1.5) and repeat. Mode 2 needs no reload, so the frequency is steadier; mode 1 needs the reload instructions, which add a few cycles of error unless they are counted in.

How does counter mode work?

With C/T = 1 the timer counts falling edges on the T0 (P3.4) or T1 (P3.5) pin instead of machine cycles, for counting objects on a conveyor or measuring frequency (count edges for one second). Sampling every machine cycle limits the input to f/24. With GATE = 1, the timer runs only while INT0 or INT1 is high, which measures a pulse width.

Predict, then check

At 11.0592 MHz, can Timer 0 in mode 2 give a 500 µs delay in one overflow?

Worked examples

5 ms delay in mode 1 · Timer 0, 11.0592 MHz
  1. N = 5 ms / 1.0851 µs = 4,608
  2. Load = 65,536 − 4,608 = 60,928 = EE00H
  3. TMOD = 01H, TH0 = EEH, TL0 = 00H

Answer: TH0 = EEH, TL0 = 00H

2 kHz square wave · Timer 0 mode 1, 11.0592 MHz, output on P1.5
  1. Period 500 µs, so each half is 250 µs
  2. N = 250 / 1.0851 = 230.4 → 230
  3. Load = 65,536 − 230 = 65,306 = FF1AH

Answer: TH0 = FFH, TL0 = 1AH; complement P1.5 at every overflow

Longest single delays · 11.0592 MHz
  1. Mode 1: 65,536 × 1.0851 µs = 71.1 ms
  2. Mode 2: 256 × 1.0851 µs = 277.8 µs
  3. Longer delays: repeat a shorter one in a loop

Answer: 71.1 ms (mode 1), 277.8 µs (mode 2)

Chapter 7

Serial communication and the UART

Which syllabus covers thisAU ET3491 Unit IVTU BEC405A Module 4SPPU 304184 Unit IMU ECC402 Modules 3.8 and 4.4KTU PBECT404 Module 4

Serial or parallel, synchronous or asynchronous?

Parallel sends 8 bits on 8 wires at once (fast over a few centimetres); serial sends them one after another on one wire, which is cheaper over metres. Synchronous links send a clock with the data (SPI, I2C); asynchronous links agree a baud rate and frame each byte with a start bit and a stop bit (the UART). Simplex goes one way, half duplex one way at a time, full duplex both ways at once.

What does a UART frame look like?

The line idles high (1). A start bit (0) tells the receiver to start timing, then 8 data bits go out least significant bit first, then a stop bit (1). So one byte costs 10 bit times. Pick a character and a baud rate and look at the line.

8051 serial port: TH1 for a baud rate and the UART frame on TxD: interactive loads as you scroll

How does the 8051 set the baud rate?

In serial mode 1, Timer 1 runs in mode 2 (TMOD = 20H) and its overflow rate sets the baud rate. With an 11.0592 MHz crystal, TH1 = FDH gives 9600 baud exactly; SMOD = 1 (PCON.7) doubles it to 19,200. The odd crystal is chosen because 11.0592 MHz / 12 / 32 = 28,800 = 3 × 9600, so the standard rates divide exactly; a 12 MHz crystal is 8.5 % off at 9600.

What do SCON, SBUF, TI and RI do?

SCON sets the mode (SM0 SM1; mode 1 = 8-bit UART), enables reception (REN) and holds the TI and RI flags; SCON = 50H is mode 1 with receive on. Writing SBUF starts a transmission and TI = 1 when the stop bit has gone; when a byte arrives it is in SBUF and RI = 1. The program must clear TI and RI itself.

Why does the 8051 need a MAX232 for RS-232?

RS-232 uses inverted, higher voltages: a 1 is −3 to −25 V and a 0 is +3 to +25 V, while the 8051's TXD and RXD are 0 and 5 V. The MAX232 converts both ways from a single 5 V supply. On a 9-pin DB-9 connector, pin 2 is RxD, pin 3 TxD and pin 5 ground. Today a USB-to-UART bridge often replaces the RS-232 port.

Predict, then check

At 9600 baud, how many bytes per second can a UART send at most?

Worked examples

TH1 for standard baud rates · 11.0592 MHz, SMOD = 0
  1. 11.0592 MHz / 384 = 28,800
  2. 9600: 28,800 / 9600 = 3 → TH1 = 256 − 3 = FDH
  3. 4800: 6 → FAH; 2400: 12 → F4H; 1200: 24 → E8H

Answer: FDH, FAH, F4H, E8H

Why not 12 MHz? · 12 MHz crystal, 9600 baud wanted
  1. 12 MHz / 384 / 9600 = 3.26, rounded to 3 (TH1 = FDH)
  2. Actual = 12 MHz / 384 / 3 = 10,417 baud
  3. Error = +8.5 %, above the ~2 % a UART link can tolerate

Answer: 8.5 % too fast, so the link fails

Time to send a word · "HELLO" at 9600 baud
  1. 5 characters × 10 bits = 50 bits
  2. 50 / 9600 = 5.208 ms

Answer: 5.208 ms

Chapter 8

Interrupts

Which syllabus covers thisAU ET3491 Unit IVTU BEC405A Module 5SPPU 304184 Unit IMU ECC402 Modules 1.2, 3.7 and 4.4KTU PBECT404 Module 4

Why use interrupts instead of polling?

Polling checks a flag in a loop and wastes the CPU while it waits. An interrupt lets the program do other work; when the event happens the CPU finishes the current instruction, pushes the PC, jumps to the interrupt service routine (ISR), and RETI brings it back to where it left off.

What are the 8051's interrupt sources and vectors?

Reset 0000H, external INT0 0003H, Timer 0 000BH, external INT1 0013H, Timer 1 001BH, serial (RI or TI) 0023H. Each vector has only 8 bytes, so it usually holds an LJMP to the real ISR. In Keil C, void isr(void) interrupt n puts the routine at 8n + 3.

How do IE and IP decide what is served?

IE enables: EA (bit 7) is the master switch, then ES, ET1, EX1, ET0, EX0. IP gives each source high or low priority. Requests that arrive together are served high priority first, then in the fixed polling order INT0, T0, INT1, T1, serial. A high-priority interrupt can also break into a low-priority ISR. Raise requests and flip the bits below.

8051 interrupts: enables, priorities and the order of service: interactive loads as you scroll

Edge- or level-triggered external interrupts?

By default (IT0 = 0) INT0 is level-triggered: a low on the pin requests service, and it must go high again before the ISR ends or it fires again. With IT0 = 1 (TCON.0) it triggers on a falling edge and the IE0 flag is cleared by hardware when the ISR starts, which suits a push button or a pulse.

What must an ISR do?

Keep it short, save any register it changes (PUSH ACC, PUSH PSW, or switch register bank), clear the flags that hardware does not clear (RI and TI must be cleared by software), and end with RETI, not RET: RETI also tells the interrupt logic that the ISR is over.

Predict, then check

INT0 and Timer 1 request at the same instant. IP = 08H (PT1 = 1). Which is served first?

Worked examples

IE for serial and Timer 0 · Enable the serial and Timer 0 interrupts only
  1. EA = 1 (bit 7), ES = 1 (bit 4), ET0 = 1 (bit 1)
  2. 1001 0010
  3. MOV IE,#92H

Answer: IE = 92H

Where does the ISR go? · Keil C: void t1_isr(void) interrupt 3
  1. Vector = 8 × n + 3
  2. 8 × 3 + 3 = 27 = 1BH

Answer: 001BH, the Timer 1 vector

5 kHz square wave from a timer interrupt · Timer 0 mode 2, 11.0592 MHz, toggle P1.2 in the ISR
  1. Half period = 100 µs
  2. N = 100 / 1.0851 = 92.16 → 92
  3. TH0 = 256 − 92 = 164 = A4H; IE = 82H (EA + ET0)

Answer: TH0 = A4H, auto-reloaded; the main program stays free

Chapter 9

LEDs, switches, 7-segment displays, keypads and LCDs

Which syllabus covers thisAU ET3491 practicals (LED, LCD, keyboard)VTU BEC405A Modules 3 and 5SPPU 304184 Units II and VMU ECC402 Modules 4.5 and 6KTU PBECT404 project topics

How are LEDs and switches connected?

A port pin can sink more current than it sources, so an LED usually goes from +5 V through a resistor (about 330 Ω to 1 kΩ) to the pin, and lights when the pin is 0. A switch connects a pin to ground with a pull-up keeping it at 1; write 1 to the pin first so it works as an input. Mechanical contacts bounce for a few milliseconds, so read twice about 10 to 20 ms apart (debounce).

How do you drive a 7-segment display?

Seven LED segments a to g (plus dp) wired to one port. Common cathode lights a segment with a 1, common anode with a 0, so the two codes are complements. To show several digits with one port, multiplex: turn on one digit at a time through a transistor and refresh all of them faster than about 50 Hz so the eye sees them steady.

7-segment display codes and multiplexing on port 1: interactive loads as you scroll

How is a 4 × 4 keypad scanned?

16 keys on 8 pins: 4 rows as outputs, 4 columns as inputs with pull-ups. Drive one row low at a time and read the columns; a 0 in a column means the key at that row and column is down. Debounce, wait for release, then look the key up in a table.

How is a 16 × 2 character LCD driven?

The HD44780-type LCD has 8 data lines and three control lines: RS (0 = command, 1 = character), R/W and E (a high-to-low pulse latches the byte). Typical start-up: 38H (8-bit, 2 lines, 5 × 7 dots), 0EH (display and cursor on), 01H (clear), 06H (move the cursor right), 80H (line 1, column 1). Line 2 starts at C0H. Wait for the busy flag (D7) or a few milliseconds between commands.

How do you switch a relay, a buzzer or a mains load?

A port pin gives only a few milliamps, so a relay coil or buzzer is driven through a transistor (or a ULN2003), with a diode across the coil to absorb the voltage spike when it switches off. An opto-isolator (LED plus phototransistor, e.g. 4N25) passes the signal through light, so the microcontroller has no electrical connection to the high-voltage side.

Predict, then check

A common-anode display shows '8' with the decimal point off. What byte goes to the port (dp on bit 7)?

Worked examples

Segment code for '2' · a = P1.0 ... g = P1.6, dp = P1.7
  1. '2' lights a, b, d, e and g
  2. Bits g f e d c b a = 1 0 1 1 0 1 1
  3. Common cathode: 0101 1011 = 5BH; common anode: complement = A4H

Answer: 5BH (CC) or A4H (CA)

Multiplexing four digits · 4 digits, whole display refreshed at 60 Hz
  1. Frame = 1 / 60 = 16.67 ms
  2. Each digit is on for a quarter: 4.17 ms
  3. Each digit has 1/4 duty, so its segment current is set higher than for a static display

Answer: 4.17 ms per digit, 240 digit switches per second

LCD cursor address · Write at line 2, column 5
  1. Line 2 starts at DDRAM address 40H; the command is 80H + 40H = C0H
  2. Column 5 is 4 places on: C0H + 4

Answer: Send command C4H with RS = 0

Chapter 10

ADC, DAC, stepper and DC motors

Which syllabus covers thisAU ET3491 practicals (ADC, DAC, stepper)VTU BEC405A Module 5SPPU 304184 Units II and IVMU ECC402 Module 6KTU PBECT404 project topics

How does the 8051 read an analog voltage?

The 8051 has no ADC, so an external one is used. The ADC0804 is an 8-bit successive-approximation converter: pulse WR to start, wait for INTR to go low, then read the byte with RD. Its full scale is twice the voltage on the Vref/2 pin (5 V if the pin is left open). The ADC0808/0809 adds an 8-channel multiplexer, selected by address lines A, B, C and latched with ALE, and signals the end of conversion on EOC.

How does a DAC0808 make a voltage?

It turns an 8-bit input into a current: each bit adds a binary-weighted share of Iref. An op-amp with a feedback resistor turns the current into a voltage. Writing a table of sine values to the DAC in a loop gives a sine wave; its frequency is set by how fast the loop runs.

How is a stepper motor driven?

A unipolar stepper has four coils; energising them in sequence through a ULN2003 pulls the rotor round one step at a time. Wave drive turns on one coil at a time, full step two (more torque), half step alternates one and two (twice the steps per revolution, smoother). The delay between steps sets the speed; reverse the table to reverse direction.

Stepper motor drive sequences: wave, full step and half step: interactive loads as you scroll

How do you control a DC motor's direction and speed?

An H-bridge such as the L293D reverses the current through the motor: two port pins pick forward, reverse or stop. Speed comes from PWM: switching the supply on and off quickly, so the motor sees the average voltage. The PIC18's CCP module makes PWM in hardware (chapter 11); on the 8051 a timer interrupt toggles the pin.

What is a data acquisition system?

Sensor, signal conditioning (amplify and filter to match the ADC range), multiplexer, ADC, microcontroller, and display or serial link. A temperature logger with an LM35 (10 mV per °C) is the usual lab example: with a 2.56 V full-scale ADC0804, one count is 10 mV, so the reading is the temperature in °C directly.

Predict, then check

A 1.8° stepper is driven in half-step mode. How many steps make one revolution?

Worked examples

ADC0804 reading · Vref/2 = 1.28 V, input 1.7 V
  1. Full scale = 2 × 1.28 = 2.56 V
  2. Step = 2.56 / 256 = 10 mV
  3. D = 1.7 / 0.01 = 170 = AAH

Answer: The ADC returns AAH (170)

DAC0808 output · Iref = 2 mA, input 99H, feedback resistor 5 kΩ
  1. 99H = 153
  2. Iout = 2 mA × 153 / 256 = 1.195 mA
  3. V = 1.195 mA × 5 kΩ = 5.98 V

Answer: 5.98 V

Stepper angle and speed · 1.8° motor, full step, 64 steps sent, 5 ms between steps
  1. Angle = 64 × 1.8 = 115.2°
  2. One revolution = 200 steps × 5 ms = 1 s
  3. Speed = 60 rpm

Answer: 115.2°; 60 rpm

Chapter 11

PIC18 architecture, peripherals and PWM

Which syllabus covers thisAU Not in the syllabusVTU Not in the syllabusSPPU 304184 Units III, IV and VMU ECC402 Module 6.1, 6.2 and 6.4KTU Not in the syllabus

How do you choose a microcontroller?

Start from the job: the speed and word size it needs, how much flash and RAM, which peripherals (ADC, PWM, UART, I2C, SPI, USB, CAN), how many pins, power draw (sleep current for a battery product), cost in volume, and the tools and support available. The 8051 family (e.g. NXP P89V51RD2), AVR (ATmega328P, the Arduino Uno chip) and PIC (PIC16F886, PIC18F4550) are the usual 8-bit choices in syllabi; ARM Cortex-M covers 32-bit work.

What is different about the PIC18 architecture?

PIC18 is a Harvard RISC: 16-bit wide instructions, an 8-bit data path built around WREG, and one instruction cycle per 4 oscillator clocks (20 MHz gives 5 million instructions per second). Data RAM is split into 256-byte banks chosen by the 4-bit BSR, and an access bank lets the most used registers be reached without switching. The PIC18F4550 has 32 KB of flash, 2 KB of RAM, 256 bytes of EEPROM, a 10-bit ADC, two CCP modules, MSSP, EUSART and USB.

What do the CONFIG bits, the watchdog and the power modes do?

Configuration bits, programmed with the code, choose the oscillator (crystal, external, internal, PLL), and turn the watchdog timer, brown-out reset and code protection on or off. The watchdog resets the chip if the program stops clearing it (CLRWDT), which recovers from a hang. SLEEP stops the clock to save power until an interrupt or the watchdog wakes it.

What can a CCP module do?

Capture copies a timer value when an input pin changes, to measure a period or pulse width. Compare acts (sets, clears or toggles a pin, or interrupts) when the timer reaches a set value. PWM makes a hardware PWM signal from Timer 2: PR2 sets the period, CCPR1L plus two DC1B bits set the 10-bit duty. Set them below and read the frequency and resolution.

PIC18 CCP PWM: frequency, resolution and duty registers: interactive loads as you scroll

How does the PIC18's built-in ADC work?

A 10-bit successive-approximation ADC with a multiplexer in front: ADCON0 picks the channel and starts the conversion (GO/DONE), ADCON1 sets which pins are analog and the reference, ADCON2 the conversion clock and justification. The result is in ADRESH:ADRESL; with a 5 V reference each count is 5 / 1024 = 4.88 mV.

Predict, then check

You keep Fosc and the prescale, and halve PR2 + 1. What happens to the PWM?

Worked examples

10 kHz PWM for a DC motor · PIC18, Fosc = 20 MHz, Timer 2 prescale 1:4, 50 % duty
  1. PR2 = 20 MHz / (4 × 4 × 10 kHz) − 1 = 124
  2. Duty steps = 4 × (124 + 1) = 500, about 8.97 bits
  3. 50 % = 250 = 0011 1110 10: CCPR1L = 3EH, DC1B = 10

Answer: PR2 = 124, CCPR1L = 3EH, DC1B1:DC1B0 = 1 0

Reading the 10-bit ADC · Vref = 5 V, ADRESH:ADRESL = 02CCH (right-justified)
  1. 02CCH = 716
  2. V = 716 × 5 / 1024 = 3.496 V

Answer: 3.496 V

Which bank holds a register? · A variable at data address 2A5H
  1. The upper 4 bits of the 12-bit address pick the bank: 2
  2. The lower 8 bits are the offset: A5H
  3. MOVLB 2 (BSR = 2), then access offset A5H with the banked bit set

Answer: Bank 2, offset A5H

Chapter 12

Serial buses: RS-485, I2C and SPI

Which syllabus covers thisAU ET3491 Unit IV (Modbus, CAN)VTU Not in the syllabusSPPU 304184 Unit VIMU ECC402 Module 6.3KTU Not in the syllabus

How is RS-485 different from RS-232?

RS-232 is single-ended, point to point and good for about 15 m. RS-485 sends each bit as the difference between two wires, so noise that hits both cancels: it runs over a kilometre at lower speeds and lets up to 32 standard loads share one twisted pair (multi-drop, usually half duplex). Modbus RTU in factories runs on RS-485.

How does I2C work?

Two open-drain wires with pull-ups, SDA (data) and SCL (clock), shared by many chips. The master sends START (SDA falls while SCL is high), a 7-bit address and a read/write bit; the addressed slave pulls SDA low for ACK. Data goes in bytes, each followed by ACK, and STOP releases the bus. Standard mode is 100 kbit/s, fast mode 400 kbit/s. Pick a slave and watch the frame.

I2C frame on SDA and SCL: start, address, ACK, data, stop: interactive loads as you scroll

How does SPI work?

Four wires: SCK (clock from the master), MOSI, MISO and one slave-select line per slave. Every clock shifts one bit out and one bit in at the same time, so SPI is full duplex, simple and fast (several MHz), but it has no addresses and no acknowledge. CPOL and CPHA pick one of four clock modes, which must match the slave's datasheet.

What is the PIC18's MSSP?

The Master Synchronous Serial Port does either SPI or I2C in hardware. In I2C master mode SSPADD sets the clock: SCL = Fosc / (4 × (SSPADD + 1)). In SPI mode SSPBUF is the shift register: write it to send, and when the flag says done, the received byte is in the same register.

What are the classic I2C and SPI lab devices?

The DS1307 real-time clock (I2C address 68H) keeps seconds to years in BCD registers 00H to 06H, running from a 32.768 kHz crystal and a backup cell, with 56 bytes of battery-backed RAM. The 24C02 is a 256-byte I2C EEPROM at address 50H to 57H (pins A2 A1 A0). SPI EEPROMs such as the 25LC series take a command byte (WREN, WRITE, READ) before the address.

Predict, then check

How many devices can a 7-bit I2C address space hold, after the reserved addresses?

Worked examples

Address byte for the DS1307 · 7-bit address 1101000 (68H)
  1. Shift left one place and add R/W
  2. Write: 1101 0000 = D0H
  3. Read: 1101 0001 = D1H

Answer: D0H to write, D1H to read

SSPADD for 100 kHz · PIC18, Fosc = 20 MHz, I2C master
  1. SCL = Fosc / (4 × (SSPADD + 1))
  2. SSPADD + 1 = 20 MHz / (4 × 100 kHz) = 50
  3. SSPADD = 49 = 31H

Answer: SSPADD = 49 (31H)

Writing 8 bytes to a 24C02 · Page write at 100 kHz
  1. Address byte + word address + 8 data bytes = 10 bytes, each 9 clocks with ACK
  2. 10 × 9 = 90 clocks = 0.9 ms (plus START and STOP)
  3. Then the EEPROM needs its internal write cycle (5 ms maximum) before the next write

Answer: About 0.9 ms on the bus + up to 5 ms write time

Chapter 13

ARM processors and embedded system design

Which syllabus covers thisAU ET3491 Unit IIVTU Not in the syllabusSPPU Not in the syllabusMU ECC402 Module 5KTU Not in the syllabus

What are the main features of the ARM7?

The ARM7TDMI is a 32-bit RISC processor with a 3-stage pipeline (fetch, decode, execute) and a von Neumann bus. T means the 16-bit Thumb instruction set (smaller code), D debug support, M a fast multiplier, I the EmbeddedICE logic. Almost every ARM instruction can be conditional, and data processing can shift an operand in the same instruction.

What is the ARM programmer's model?

In any mode the program sees 16 registers R0 to R15 plus the CPSR. R13 is the stack pointer, R14 the link register (BL saves the return address there) and R15 the program counter. The CPSR holds the N, Z, C, V flags, the interrupt disable bits and the mode. Seven modes (User, FIQ, IRQ, Supervisor, Abort, Undefined, System) have some banked registers of their own, 37 registers in all, so an interrupt can start without saving them.

Cortex-A, Cortex-R and Cortex-M: which is which?

Cortex-A (application) runs Linux or Android with an MMU, in phones and infotainment. Cortex-R (real-time) is for fast, deterministic control such as disk drives and automotive safety units. Cortex-M (microcontroller) is the low-cost, low-power family (M0 to M7) with a built-in interrupt controller, the NVIC; STM32 chips are Cortex-M.

How does an ARM handle exceptions?

On an exception the core saves the CPSR into the new mode's SPSR, puts the return address in its R14, switches mode, disables further IRQs and jumps to a fixed vector (reset at 0x00, undefined 0x04, SWI 0x08, prefetch abort 0x0C, data abort 0x10, IRQ 0x18, FIQ 0x1C). FIQ has extra banked registers, so it can be served fastest. Software interrupts (SWI) are how user code asks the supervisor-mode OS for a service.

What are the steps of embedded system design?

Requirements (what the user needs, including cost, power and size), specification (exactly what the system does), architecture (the blocks, and which are hardware or software), components (choose or design each one), then system integration and testing. The model train controller is the textbook example: a console sends speed and direction commands over a serial link to a controller on each train.

Predict, then check

Why does a 3-stage pipeline not make one instruction run 3 times faster?

Worked examples

Pipeline throughput · 100 instructions, no branches, 3-stage pipeline
  1. Without a pipeline: 3 × 100 = 300 cycles
  2. With it: the first finishes after 3 cycles, then one per cycle: 100 + 2 = 102
  3. Speed-up = 300 / 102 ≈ 2.9

Answer: 102 cycles instead of 300

Calling and returning · BL func at address 0x8000 (ARM state)
  1. BL puts the address of the next instruction, 0x8004, in R14 (LR)
  2. func ends with MOV PC, LR (or BX LR)
  3. A function that calls another must first push LR on the stack

Answer: Return address 0x8004 in R14

Chapter 14

Real-time operating systems and IoT

Which syllabus covers thisAU ET3491 Units III, IV and VVTU Not in the syllabusSPPU Not in the syllabusMU Not in the syllabusKTU Not in the syllabus

What does a real-time operating system add?

An RTOS runs several tasks (processes) on one CPU and guarantees that each meets its deadline. Each task is ready, running or blocked; a preemptive priority scheduler always runs the highest-priority ready task and switches the moment a more important one becomes ready. Hard real time means a missed deadline is a failure (an airbag); soft real time means it only degrades the result (a video frame).

What is rate-monotonic scheduling?

Give the task with the shortest period the highest priority. Liu and Layland (1973) proved that n periodic tasks always meet their deadlines if the CPU utilisation U = Σ C/T is at most n(2^(1/n) − 1): 82.8 % for 2 tasks, 78.0 % for 3, falling towards 69.3 %. Above the bound a task set may still work, which a response-time check or a timeline shows. Change the run times below.

Rate-monotonic scheduling timeline for three RTOS tasks: interactive loads as you scroll

How do tasks share data safely?

Through the RTOS: semaphores and mutexes guard shared resources, message queues and mailboxes pass data, and events or signals wake tasks. Priority inversion happens when a low-priority task holds a mutex that a high-priority task needs and a medium task preempts it; priority inheritance (temporarily raising the holder's priority) fixes it, as NASA's Mars Pathfinder showed in 1997.

What makes up an IoT system?

Devices with sensors and actuators (often a microcontroller or a Raspberry Pi), connectivity (Wi-Fi, BLE, Zigbee, cellular), a gateway, a cloud or local server that stores and analyses the data, and an application for the user. IoT differs from M2M in using IP networks and cloud platforms rather than closed point-to-point links. NETCONF and the YANG data model are used to configure and manage IoT devices.

Which IoT and industrial protocols should you know?

MQTT: light publish/subscribe through a broker over TCP, with QoS levels 0, 1 and 2; XMPP: XML messaging, originally for chat; Modbus: master/slave register reads and writes over RS-485 (RTU) or TCP; CAN: a multi-master, differential bus where the lowest message ID wins arbitration, used in every car; BACnet: building automation (HVAC, lighting).

Predict, then check

Three tasks have U = 83 %, above the 78 % bound for n = 3. Under rate-monotonic scheduling they will:

Worked examples

Rate-monotonic check · Tasks (C, T) = (1, 4), (2, 6), (3, 12) ms
  1. U = 1/4 + 2/6 + 3/12 = 83.3 %
  2. Bound for n = 3: 3(2^(1/3) − 1) = 77.98 %, so the bound does not settle it
  3. Response time of task 3: R = 3 + ⌈R/4⌉·1 + ⌈R/6⌉·2, iterate from 6: 7, 9, 10, 10
  4. R = 10 ms ≤ 12 ms

Answer: All deadlines met (task 3 finishes at 10 ms)

Utilisation limit for many tasks · n → ∞
  1. n(2^(1/n) − 1) → ln 2
  2. ln 2 = 0.6931

Answer: 69.3 % always works under RMS

Keep going

Recommended reading

  • The 8051 Microcontroller and Embedded Systems Using Assembly and C, M. A. Mazidi, J. G. Mazidi and R. D. McKinlay
  • The 8051 Microcontroller, Kenneth J. Ayala
  • PIC Microcontroller and Embedded Systems, M. A. Mazidi, R. D. McKinlay and D. Causey
  • Microcontrollers: Theory and Applications, Ajay V. Deshmukh
  • Computers as Components, Marilyn Wolf
  • ARM System-on-Chip Architecture, Steve Furber
  • Internet of Things: A Hands-on Approach, Arshdeep Bahga and Vijay Madisetti

How this book was made

Chapters follow the official syllabi listed above. Every interactive's formulas and every worked-example number were checked by script. Explanations, animations and examples are original to Skill-Lync.

From the exam to a core job

Talk to a counsellor.

Ask how embedded engineers use microcontrollers on real projects, and what the Pre-Graduate Program in Embedded Systems covers.

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.

Talk to a career counsellor

Talk to a career counsellor

Free 20-minute call. We'll map the right course to where you want to work.

By submitting you agree to our Terms and Privacy Policy.