Microcomputer Project Lab
Hands-on microcontroller design, A/D conversion, interfacing sensors, motors, and LCD displays.
Microcontroller Architecture and Programming
What is a Microcontroller? A microcontroller (MCU) is a complete computer on a chip: CPU core Flash memory (program) RAM (data) Peripherals (GPIO, timers, ADC, UART, SPI, I2C) Clock and power manag...
What is a Microcontroller?
A microcontroller (MCU) is a complete computer on a chip:
- CPU core
- Flash memory (program)
- RAM (data)
- Peripherals (GPIO, timers, ADC, UART, SPI, I2C)
- Clock and power management
Unlike a microprocessor (which needs external RAM, ROM, and I/O), an MCU is self-contained. Perfect for embedded control.
Popular MCU Families
- 8-bit: ATmega (Arduino), PIC, 8051
- 16-bit: MSP430 (ultra-low power)
- 32-bit: ARM Cortex-M (STM32, nRF), ESP32, RISC-V
- DSP: TI C2000, ADI SHARC
ARM Cortex-M dominates the 32-bit space.
Memory Map
Typical MCU layout (ARM Cortex-M):
- 0x00000000: Flash (program)
- 0x20000000: SRAM (data)
- 0x40000000: Peripherals (GPIO, timers, UART)
- 0xE0000000: System control (NVIC, SysTick)
Memory-mapped I/O: peripherals are accessed like memory. Reading/writing a register controls the hardware.
GPIO
General-Purpose Input/Output pins. Each pin can be:
- Input (read external state)
- Output (drive high or low)
- Alternate function (UART, SPI, etc.)
- Analog (ADC input)
Configured via registers:
// Set pin 5 as output (AVR)
DDRB |= (1 << 5);
PORTB |= (1 << 5); // high
Or via HAL:
HAL_GPIO_WritePin(GPIOA, GPIO_PIN_5, GPIO_PIN_SET);
Bit Manipulation
Embedded C uses bit operations extensively:
x |= (1 << n); // set bit n
x &= ~(1 << n); // clear bit n
x ^= (1 << n); // toggle bit n
y = (x >> n) & 1; // read bit n
Bit fields and macros make this cleaner:
#define BIT(n) (1 << (n))
#define SET_BIT(reg, bit) ((reg) |= BIT(bit))
Interrupts
External events trigger interrupts. The CPU:
- Saves context
- Jumps to ISR (interrupt service routine)
- Executes ISR
- Restores context
- Returns to main
Keep ISRs short. Do heavy work in the main loop.
Timers and Counters
Hardware timers count clock edges:
- Generate delays without blocking
- Measure pulse widths
- Generate PWM
- Count external events
16-bit timer at 16 MHz: max period = 65535/16e6 = 4 ms. Prescaler extends range.
ADC (Analog to Digital Converter)
Converts analog voltage to digital number:
- Resolution: 8, 10, 12, 16 bits
- Sample rate: up to MSps
- Input range: typically 0 to V_ref
Example: 12-bit ADC with V_ref = 3.3 V gives 3.3/4096 = 0.8 mV resolution.
Serial Protocols
- UART: asynchronous, 2 wires (TX/RX)
- SPI: synchronous, 4 wires, high speed
- I2C: synchronous, 2 wires, multiple devices
Each has trade-offs. UART simplest, SPI fastest, I2C most devices.
Programming Workflow
- Write C code
- Compile with cross-compiler (gcc-arm-none-eabi)
- Link with startup and libraries
- Program flash via JTAG/SWD/bootloader
- Debug via GDB + hardware debugger
Tools: Arduino IDE, PlatformIO, STM32CubeIDE, ESP-IDF.
Key Takeaways
- MCU = CPU + memory + peripherals on one chip
- Memory-mapped I/O for peripherals
- GPIO for digital I/O, configured by registers
- Interrupts for responsive event handling
- Timers for delays, PWM, measurement
- ADC for analog input
- UART/SPI/I2C for serial communication
- Cross-compile and flash via debugger
Interfacing Sensors and Actuators
Sensors Overview Sensors convert physical quantities to electrical signals: Temperature: thermistor, RTD, thermocouple, digital (DS18B20, DHT22) Pressure: strain gauge, piezo, capacitive Ligh...
Sensors Overview
Sensors convert physical quantities to electrical signals:
- Temperature: thermistor, RTD, thermocouple, digital (DS18B20, DHT22)
- Pressure: strain gauge, piezo, capacitive
- Light: photoresistor (LDR), photodiode, digital (BH1750)
- Motion: PIR, accelerometer, gyroscope, IMU
- Distance: ultrasonic (HC-SR04), IR, laser (VL53L0X)
- Humidity: capacitive, resistive
Each has specific interface requirements.
Analog Sensors
Output voltage or current proportional to the physical quantity.
Thermistor: resistance varies with temperature. Need voltage divider + ADC.
Strain gauge: tiny resistance change under strain. Need instrumentation amplifier (INA) + ADC.
Photodiode: tiny current. Need transimpedance amplifier (TIA) + ADC.
Analog sensors need signal conditioning: amplification, filtering, level shifting.
Digital Sensors
On-chip ADC and digital interface (I2C or SPI).
DS18B20: 1-Wire digital temperature. Range -55 to +125°C, ±0.5°C accuracy.
BME280: I2C/SPI. Temperature, humidity, pressure.
MPU6050: I2C. 3-axis accelerometer + 3-axis gyroscope.
Advantages: no external ADC, calibrated, digital noise immunity.
I2C Communication
Two wires: SDA (data) and SCL (clock). Multiple devices share the bus.
Wire.beginTransmission(0x68); // MPU6050 address
Wire.write(0x75); // WHO_AM_I register
Wire.endTransmission(false);
Wire.requestFrom(0x68, 1);
byte id = Wire.read();
Pull-up resistors on both lines (2.2k-10k). Speeds: 100 kHz, 400 kHz, 1 MHz.
SPI Communication
Four wires: MOSI, MISO, SCK, CS.
digitalWrite(CS, LOW);
SPI.transfer(0x80 | reg);
byte value = SPI.transfer(0x00);
digitalWrite(CS, HIGH);
Faster than I2C (up to 50 MHz), but needs one CS per device.
Actuators
Output devices:
- LEDs: direct (with resistor), or via transistor for high power
- Relays: switch AC/DC loads, need driver + flyback diode
- Motors: DC, stepper, servo — need H-bridge or driver IC
- Solenoids: like relays, inductive load
- Piezo buzzers: direct or via transistor
- Displays: LCD, OLED, e-ink, TFT
Driving Loads
GPIO can source/sink ~20 mA. For more, use:
- BJT: current-controlled, need base resistor
- MOSFET: voltage-controlled, logic-level needed
- Relay: opto-isolated module recommended
Example MOSFET circuit:
GPIO ── 220Ω ── Gate
│
10kΩ to GND
Drain ── Load ── +12V
Source ── GND
PWM for Actuator Control
Pulse-width modulation controls average power:
- LED dimming: 1-2 kHz
- Motor speed: 10-25 kHz
- Servo position: 50 Hz, 1-2 ms pulses
- Heater: 1 Hz
AnalogWrite() on Arduino, LEDC on ESP32.
Motor Drivers
H-bridge: controls direction + speed of DC motor. L293D, L298N, DRV8833.
Stepper driver: A4988, DRV8825. Takes step + direction signals.
Servo: built-in control, just send pulses.
Sensor Fusion
Combining multiple sensors for better accuracy:
- IMU: accelerometer + gyroscope + magnetometer
- Kalman filter or complementary filter
- E.g., Bosch BNO055 does fusion in hardware
Signal Conditioning
- Amplification: op-amp for small signals
- Filtering: RC low-pass to remove noise
- Isolation: opto-couplers for high voltage
- Level shifting: 3.3V ↔ 5V with MOSFETs or dedicated ICs
Key Takeaways
- Many sensor types: analog, digital, MEMS
- I2C/SPI for digital sensors
- GPIO drives small loads; MOSFETs/BJTs for larger
- PWM controls power to actuators
- Motor drivers for DC, stepper, servo
- Sensor fusion improves accuracy
- Signal conditioning is often required
Real-Time Programming Techniques
The Superloop Simple structure: while (1) { read_sensors(); update_state(); drive_outputs(); } Works for simple tasks. Fails when timing is critical or tasks compete. ...
The Superloop
Simple structure:
while (1) {
read_sensors();
update_state();
drive_outputs();
}
Works for simple tasks. Fails when timing is critical or tasks compete.
Cooperative Scheduling
Each task runs when it's ready:
while (1) {
if (time_for_task_a()) task_a();
if (time_for_task_b()) task_b();
// never blocks
}
Each task must return quickly. No long delays.
Non-Blocking Delays
Never use delay() in a loop with multiple tasks. Instead:
unsigned long last = 0;
const unsigned long INTERVAL = 100;
void loop() {
if (millis() - last >= INTERVAL) {
last = millis();
do_periodic_work();
}
do_other_work();
}
millis() rolls over every ~49 days. The subtraction is rollover-safe.
State Machines
Replace nested if/else with explicit states:
enum State { IDLE, HEATING, COOLING };
State current = IDLE;
void loop() {
switch (current) {
case IDLE:
if (temp < setpoint - 1) current = HEATING;
break;
case HEATING:
heater_on();
if (temp >= setpoint) current = IDLE;
break;
case COOLING:
fan_on();
if (temp <= setpoint) current = IDLE;
break;
}
}
Clearer, easier to modify, less buggy.
Interrupt-Driven Design
Main loop handles logic; ISRs handle timing-critical events:
volatile bool button_pressed = false;
void button_isr() {
button_pressed = true;
}
void loop() {
if (button_pressed) {
button_pressed = false;
handle_button();
}
}
Use volatile for variables shared between ISR and main.
Watchdog Timer
Reset the CPU if it hangs:
wdt_enable(WDTO_2S); // 2 second timeout
void loop() {
wdt_reset(); // feed the watchdog
do_work();
}
If do_work() hangs for 2s, the CPU resets. Recovers from lockups.
Watchdog for Reliability
For deployed devices:
- Enable watchdog
- Log reset reason on startup
- Retry failed operations
- Use brown-out detection
An ESP32 in the field may run for years. The watchdog is essential.
Real-Time Constraints
Some operations must complete within a deadline:
- Motor commutation: microseconds
- Control loops: milliseconds
- User interface: ~100 ms
- Data logging: seconds
Match technique to constraint:
- Microseconds: hardware peripherals, DMA
- Milliseconds: interrupt-driven, RTOS
- Seconds: cooperative scheduling
Power Management
For battery-powered devices:
- Sleep modes (idle, standby, deep sleep)
- Wake on interrupt or timer
- Turn off unused peripherals
- Lower clock frequency
- Use DMA to avoid CPU wake-ups
ESP32 deep sleep: 10 µA. Wake every 5 min for 3s: average current ~80 µA.
Debugging Techniques
- printf debugging: simple, effective, but slow
- Logic analyzer: capture digital signals
- Oscilloscope: view analog waveforms
- JTAG/SWD: step through code
- LED toggling: poor man's trace
- Serial logging: extensive, structured
Common Bugs
- Buffer overflow: reading beyond array bounds
- Race condition: ISR and main accessing shared data
- Non-volatile variable: compiler optimizes away
- Stack overflow: recursion or large local variables
- Watchdog reset loop: main loop starves watchdog
- Priority inversion: with RTOS
Key Takeaways
- Superloop for simple tasks
- Cooperative scheduling with non-blocking delays
- State machines for complex logic
- Interrupts for timing-critical events
- Watchdog for reliability
- Power management for battery life
- Match technique to timing constraint
- Debug with scope, logic analyzer, JTAG
- Watch for classic embedded bugs
Communication Protocols in Embedded Systems
UART — Universal Asynchronous Receiver/Transmitter Two wires (TX, RX). No clock. Baud rate agreed in advance. Frame: start bit, 7-8 data bits, optional parity, stop bit(s). Common baud: 9600, 115200,...
UART — Universal Asynchronous Receiver/Transmitter
Two wires (TX, RX). No clock. Baud rate agreed in advance.
Frame: start bit, 7-8 data bits, optional parity, stop bit(s).
Common baud: 9600, 115200, 921600.
Serial.begin(115200);
Serial.println("Hello");
if (Serial.available()) {
char c = Serial.read();
}
Pros: simple, universal. Cons: point-to-point, modest speed.
I2C — Inter-Integrated Circuit
Two wires (SDA, SCL). Multi-drop: up to 127 devices, each with unique address.
7-bit addressing. Standard speeds: 100 kHz, 400 kHz, 1 MHz.
Needs pull-up resistors: typically 4.7kΩ.
Wire.begin();
Wire.beginTransmission(0x48);
Wire.write(0x00);
Wire.endTransmission();
Wire.requestFrom(0x48, 2);
Pros: only 2 pins for many devices. Cons: slower, sensitive to bus capacitance.
SPI — Serial Peripheral Interface
Four wires (SCLK, MOSI, MISO, CS). Full duplex. High speed (10-50 MHz).
Each device needs its own CS pin.
SPI.begin();
digitalWrite(CS, LOW);
SPI.transfer(0x80);
uint8_t high = SPI.transfer(0x00);
uint8_t low = SPI.transfer(0x00);
digitalWrite(CS, HIGH);
Pros: fast, full duplex. Cons: more pins, no standard addressing.
CAN — Controller Area Network
Automotive standard. Two wires (CANH, CANL), differential.
Multi-master. Priority via message ID. Automatic retransmission. CRC.
Speed: up to 1 Mbps (classic), 8 Mbps (CAN FD).
Used in every modern car for engine, brakes, dashboard.
// With MCP2515 controller
CAN.sendMsgBuf(0x100, 0, 8, data);
RS-485
Differential serial for industrial environments. Up to 1200 m cable, 10 Mbps.
Multi-drop: up to 32 devices (or 256 with repeaters).
Used with Modbus protocol in factory automation.
Modbus
Industrial protocol. Master-slave. Runs over RS-485 or TCP.
Data model: coils (bits), discrete inputs, holding registers, input registers.
// Read holding register 100 on slave 1
uint16_t value = modbus.readHoldingRegister(1, 100);
1-Wire
Single wire + ground. Dallas Semiconductor (now Maxim).
Used for DS18B20 temperature sensors, iButton.
Addressing: 64-bit unique ID per device.
sensors.requestTemperatures();
float temp = sensors.getTempCByIndex(0);
MQTT
High-level protocol over TCP. Publish-subscribe.
Broker (Mosquitto, EMQX) routes messages. Clients publish to topics and subscribe.
Topics hierarchical: home/livingroom/temperature.
QoS levels: 0 (at most once), 1 (at least once), 2 (exactly once).
client.publish("home/temp", "22.5");
client.subscribe("home/+/setpoint");
Used in IoT, smart home, industrial.
LoRa / LoRaWAN
Long-range, low-power wireless. 10-15 km range in rural areas.
Data rate: 0.3-50 kbps. Very low power.
Used for remote sensors, smart agriculture, city infrastructure.
BLE — Bluetooth Low Energy
Wireless, low-power. Pairs with phones.
GATT profile: services and characteristics.
Used in wearables, beacons, medical devices.
Choosing the Right Protocol
| Need | Protocol |
|------|----------|
| Simple serial | UART |
| Many sensors, few pins | I2C |
| High speed, chip-to-chip | SPI |
| Automotive | CAN |
| Industrial, long cable | RS-485 |
| IoT, WiFi/internet | MQTT |
| Long range, low power | LoRa |
| Phone pairing | BLE |
Key Takeaways
- UART: simple, point-to-point
- I2C: many devices, 2 pins, moderate speed
- SPI: fast, full-duplex, more pins
- CAN: automotive, robust, prioritized
- RS-485/Modbus: industrial, long cable
- MQTT: IoT, publish-subscribe, over TCP
- LoRa: long-range, low-power wireless
- BLE: phone pairing, wearables
- Choose based on speed, range, power, cost
Embedded Systems Project Design
From Idea to Product Embedded development is not just coding. It's: 1. Requirements (what does it need to do?) 2. Architecture (how is it organized?) 3. Hardware design (schematic, PCB) 4....
From Idea to Product
Embedded development is not just coding. It's:
- Requirements (what does it need to do?)
- Architecture (how is it organized?)
- Hardware design (schematic, PCB)
- Firmware design (modules, interfaces)
- Testing (unit, integration, HIL)
- Deployment (programming, calibration)
- Maintenance (updates, bug fixes)
Requirements
Functional: what the device does.
Non-functional:
- Timing (response time, sample rate)
- Power (battery life, quiescent current)
- Cost (BOM, assembly)
- Size, weight
- Environmental (temperature, humidity, shock)
- Regulatory (FCC, CE, UL)
- Reliability (MTBF, mission lifetime)
Write requirements before designing.
Architecture
Block diagram showing:
- MCU and its peripherals
- Sensors and actuators
- Communication interfaces
- Power supply
- External interfaces (USB, display, buttons)
Decide early: what runs on MCU, what runs in hardware, what runs on the cloud.
Hardware Design
Schematic capture → PCB layout → fabrication → assembly → test.
Key considerations:
- Power supply (LDO vs buck, efficiency)
- Decoupling capacitors on every IC
- Ground planes
- Trace width for current
- Connectors and mounting holes
- Test points for debugging
Firmware Architecture
Layered:
- HAL (Hardware Abstraction Layer): register-level drivers
- Drivers: GPIO, UART, SPI, I2C, timers
- Middleware: RTOS, filesystems, network stacks
- Application: business logic
Each layer tested separately.
Modular Design
Each module has:
- A clear interface (header file)
- A single responsibility
- Unit tests
Example modules for a data logger:
sensor.c— reads temperaturestorage.c— writes to SD cardcomms.c— sends over Wi-Fimain.c— orchestrates
Version Control
Use git for firmware:
- Commit often
- Tag releases
- Branch for features
- .gitignore for build artifacts
For collaborative work: code review, CI.
Testing
Unit tests: each module in isolation, on host.
Integration tests: modules together, on target.
Hardware-in-the-loop (HIL): real hardware, automated test.
Field testing: actual deployment conditions.
Automated testing catches regressions early.
Debugging Tools
- printf: simple, but slows code
- SWD/JTAG: step through code, inspect variables
- Logic analyzer: view SPI/I2C/UART traffic
- Oscilloscope: analog signals, timing
- Power profiler: measure current draw over time
- Segger RTT: fast printf alternative
Power Budget
Sum the current draw of every component in every state:
- Active: MCU + sensors + radio
- Idle: MCU low-power + sensors off
- Sleep: only RTC + wake source
Weight by duty cycle to get average current.
Example:
- 10 mA for 3s every 5 min: 10 × 3 / 300 = 0.1 mA average
- 10 µA in deep sleep: 0.01 mA
- Total: 0.11 mA
- Battery 2000 mAh: 18,000 hours = 2 years
Cost Optimization
- Choose parts with multiple sources
- Reduce BOM count (integrate functions)
- Use MCU with all needed peripherals
- Consider assembly cost (SMT vs THT)
- Volume pricing
A $1 difference in BOM = $10,000 per 10k units.
Deployment
- Production programming (bulk flash)
- Calibration (per unit)
- Testing (functional test)
- Packaging and shipping
Field Updates
- OTA firmware update (Wi-Fi, cellular, BLE)
- Bootloader with rollback
- Signed firmware for security
- Staged rollout (small % first)
Maintenance
- Remote diagnostics (logs to cloud)
- Bug reports from users
- Crash dump analysis
- Metrics (uptime, error rates)
Key Takeaways
- Requirements first, then design
- Layered firmware architecture
- Modular, testable modules
- Version control everything
- Multiple testing levels (unit, integration, HIL, field)
- Power budget drives battery life
- Cost optimization at scale
- Deployment needs production programming
- OTA updates are essential for IoT
- Maintenance is ongoing
📝 Problem Set 1: GPIO, Interrupts, Communication
Q1. Write C code to blink an LED on GPIO 5 every 500 ms using non-blocking millis().
Show Solution
unsigned long last = 0; void loop() { if (millis() - last >= 500) { last = millis(); digitalWrite(5, !digitalRead(5)); } }
Q2. Design an I2C temperature sensor interface. Why are pull-up resistors needed, and what value?
Show Solution
I2C lines are open-drain: the bus can only be pulled LOW. Pull-ups (2.2kΩ-10kΩ) restore HIGH when no device is pulling. Lower values → faster rise, more current. Higher values → slower rise, less current. Use 4.7kΩ for 100 kHz, 2.2kΩ for 400 kHz with typical bus capacitance.
Q3. Write pseudocode to read an HC-SR04 ultrasonic sensor and convert the echo time to distance.
Show Solution
digitalWrite(TRIG, LOW); delayMicroseconds(2); digitalWrite(TRIG, HIGH); delayMicroseconds(10); digitalWrite(TRIG, LOW); duration = pulseIn(ECHO, HIGH); distance_cm = duration × 0.034 / 2;
🎯 Midterm 1: Architecture, Peripherals, Protocols
Q1. Choose between UART, I2C, SPI, and CAN for: (a) SD card, (b) temperature sensor, (c) automotive ECU, (d) USB-serial debug. Justify.
Show Solution
(a) SD card: SPI (fast, 25 MHz, simple). (b) Temperature sensor: I2C (2 wires, multiple devices). (c) Automotive ECU: CAN (differential, robust, priority). (d) USB-serial: UART (direct PC communication).
Q2. Explain how an ISR and the main loop should cooperate to handle a button press without losing events.
Show Solution
ISR: sets a volatile flag or pushes event into a queue. ISR must be short — no heavy processing. Main loop polls flag/queue and does the real work. Use volatile for shared variables, and a mutex or critical section if data is complex. Alternatively use FreeRTOS notification.
Q3. A 12-bit ADC with Vref = 3.3V reads 2048. What is the input voltage? What is the resolution in mV/LSB?
Show Solution
Resolution = 3.3 / 4096 = 0.806 mV/LSB. Reading 2048 → V = 2048 × 0.806mV = 1.65 V (mid-scale).