Peripheral Interfacing
Peripherals are the bridge between your microcontroller and the physical world. Understanding how to configure and control GPIOs, timers, interrupts, and external sensors is fundamental to embedded systems development.
General Purpose I/O (GPIO)
GPIOs are the most basic form of peripheral—digital pins that can be configured as inputs or outputs to interact with external components.
GPIO Configuration
- Direction: Input or Output mode
- Pull-up/Pull-down: Internal resistors to define default state
- Push-Pull vs Open-Drain: Output driver configuration
- Speed/Slew Rate: How fast the pin can toggle (affects EMI)
- Alternate Function: Map pin to specific peripheral (UART, SPI, etc.)
Reading Digital Inputs
⚠️ Debouncing: Mechanical switches bounce when pressed, causing multiple false triggers. Always implement software or hardware debouncing!
Timers and Counters
Timers are essential for creating precise delays, generating PWM signals, measuring pulse widths, and scheduling periodic tasks.
Timer Modes
- Basic Timer: Simple counting for delays and time measurement
- PWM Generation: Create pulse-width modulated signals
- Input Capture: Measure external signal timing
- Output Compare: Trigger actions at specific count values
- Encoder Mode: Interface with rotary encoders
Interrupts
Interrupts allow the MCU to respond immediately to events without constantly polling, making your code more efficient and responsive.
Interrupt Types
- External Interrupts: Triggered by GPIO pin changes (rising/falling edge)
- Timer Interrupts: Triggered when timer overflows or matches a value
- Communication Interrupts: UART RX complete, SPI transfer done, etc.
- DMA Interrupts: Data transfer complete notifications
- System Interrupts: SysTick, fault handlers, reset
Writing an ISR (Interrupt Service Routine)
💡 Best Practice: Keep ISRs short! Set a flag and do the heavy work in the main loop or a task. Avoid blocking calls and printf in ISRs.
Sensor Integration
Sensors convert physical quantities into electrical signals. Common interfaces include analog (ADC), digital (GPIO), and protocol-based (I2C, SPI).
Common Sensor Types
- Temperature: LM35 (Analog), DS18B20 (1-Wire), BMP280 (I2C/SPI)
- Motion/IMU: MPU6050 (I2C), LSM6DS3 (SPI)
- Proximity/Distance: HC-SR04 (Ultrasonic), VL53L0X (ToF/I2C)
- Light: LDR (Analog), BH1750 (I2C)
- Humidity: DHT22 (1-Wire), SHT31 (I2C)
Example: Reading I2C Temperature Sensor
Display Interfacing
Displays provide visual feedback. Common types include character LCDs, graphic LCDs, OLEDs, and seven-segment displays.
Popular Display Interfaces
- HD44780 Character LCD: 4-bit or 8-bit parallel interface
- SSD1306 OLED: I2C or SPI, 128x64 pixels
- ST7735 TFT: SPI, color graphics
- MAX7219: SPI, for LED matrices and 7-segment displays
🎯 Key Takeaway: Mastering peripheral interfacing unlocks the ability to connect your embedded system to virtually any sensor, actuator, or display—bringing your projects to life!