🦾 Mechatronic Applications
🎯 (SE-11-03)
📌 Outline applications of mechatronic systems in a variety of specialised fields. Mechatronics involves the synergy of mechanical, electrical, and software engineering to create intelligent machines.
🕹️ Microcontrollers & Hardware
🎯 (SE-11-01, SE-11-03)
📌 Identify hardware requirements and Assess the relationship between microcontrollers and traditional CPUs.
⚙️ Microcontrollers vs CPUs
A Microcontroller (e.g., ATmega328P on an Arduino) is an integrated circuit containing a processor, memory (RAM/Flash), and I/O peripherals on a single chip. In contrast, a traditional CPU requires external components (RAM, Storage, Northbridge) to function. Microcontrollers are preferred for mechatronics because they allow direct, real-time control of hardware pins, are cost-effective, and have significantly lower power requirements than general-purpose CPUs.
| Concept | Description & Relationship |
|---|---|
| 📜 Instruction Set | The predefined set of basic commands (Opcodes) that a processor understands. Mechatronic code must be compiled for a specific instruction set (e.g., ARM or AVR). |
| 🛠️ Registers | Data Registers store temporary values being processed (like a sensor reading), while Address Registers hold the memory location of the next instruction. |
🌡️ Sensors, Actuators & Manipulators
🎯 (SE-11-06)
📌 Identify and Describe the hardware used in mechatronic systems to sense and react to the physical world.
🌡️ Sensors (Inputs)
Devices that convert physical properties into electrical signals.
- 🔘 Motion: PIR (Passive Infrared) sensors detect heat radiation moving across a background.
- 💡 Light: LDRs (Light Dependent Resistors) change resistance based on ambient light levels.
🎯 Actuators (Outputs)
Components that convert electrical energy into physical motion.
- 💧 Hydraulic: Utilise pressurised fluid to generate high force (e.g., in excavators).
- ⚡ Electric: DC motors or Servos that provide rotational movement.
🦾 Manipulators
The parts of the system that physically interact with objects.
- 🗜️ Robotic Gripper: An end effector designed to grasp and release objects.
- 🔄 Degrees of Freedom: The number of independent directions in which a robot can move.
from machine import Pin, PWM
import utime
sensor = Pin(14, Pin.IN) # Motion sensor
servo = PWM(Pin(15)) # Actuator
while True:
if sensor.value() == 1:
servo.duty_u16(5000) # Move to specific angle
else:
servo.duty_u16(2000) # Return to home
utime.sleep(0.1)
📊 Mechatronic Data Processing
🎯 (SE-11-04)
📌 Use and Understand how data is obtained and processed, including diagnostic data for system optimisation.
📊 Processing and Diagnostic Data
Mechatronic systems process raw analog signals (via ADCs) into digital data for decision-making. Diagnostic Data involves monitoring internal states—such as motor temperature, battery voltage, or current draw—to identify potential hardware failures before they occur. Optimisation Data is used to refine control algorithms, such as adjusting the duty cycle of a PWM signal to achieve maximum motor efficiency with minimal heat generation. Engineers use this data to perform "Predictive Maintenance", replacing components before a system-critical failure happens.
🔢 Analog-to-Digital Conversion (ADC)
Sensors output continuous analog voltages. Microcontrollers use Analog-to-Digital Converters to sample these voltages and convert them to digital numbers for processing. An ADC typically has a resolution (e.g., 8-bit, 10-bit, 12-bit), determining how many discrete voltage levels it can represent.
ADC Formula: Digital Value = (Measured Voltage / Reference Voltage) × (2^Resolution - 1)
🌏 Example: A 10-bit ADC (1024 levels, 0-1023) with 5V reference, measuring 2.5V:
- Digital Value = (2.5 / 5) × (2^10 - 1) = 0.5 × 1023 = 511.5 ≈ 511 (raw value)
- This 511 value is then used in software to make decisions—for example, if the voltage from a temperature sensor crosses a threshold, trigger a cooling system.
⚙️ Software Control and Dependencies
🎯 (SE-11-02)
📌 Experiment with software to control interactions and dependencies within mechatronic systems, understanding motion constraints, degrees of freedom, and how subsystems combine.
📐 Motion Constraints and Degrees of Freedom
Motion Constraints are limitations on how a mechanical system can move, imposed by its physical design (e.g., a robotic arm pivot can only rotate within a specific range; a gripper can only open/close). Degrees of Freedom (DOF) refers to the number of independent directions in which a system can move. A gripper has 1 DOF (open/close); a planar robotic arm has 2 DOF (up/down, left/right); a full 3D robot arm has 6 DOF or more. Software must account for these constraints when generating movement commands—exceeding constraints can cause mechanical damage.
🧩 Combination of Subsystems
Complex mechatronic systems are built by combining simpler subsystems. For example, an automated warehouse robot combines: (1) a vision subsystem to identify items, (2) a navigation subsystem to move through the warehouse, (3) a gripper subsystem to pick items, and (4) a communication subsystem to report status. Software must coordinate these subsystems safely—ensuring the gripper only activates when the robot is stationary, and navigation only occurs when the gripper is closed.
🔌 Combination of Sensors, Actuators, and End Effectors
Viable subsystems require careful integration of sensors (inputs), actuators (outputs), and end effectors (the working tool). For example, a 3D printer subsystem combines:
- Sensors: position encoders, temperature sensors, filament detection
- Actuators: stepper motors for X/Y/Z axes, heater elements
- End Effector: the extruder nozzle
Software must synchronise these components—heating the nozzle only when filament is loaded, coordinating multiple motors to move the print head smoothly, and monitoring temperature feedback.
🦾 System Diagram - Mechatronic System
Integration of sensors, control, and actuators
This diagram shows the complete flow of a mechatronic system: sensors collect data from the environment, the microcontroller processes that data and makes decisions, actuators execute commands based on the microcontroller's output, and end effectors perform the desired physical action. Power supply feeds all components to enable the entire integrated system.
• Camera
• Ultrasonic
• IMU gyro
• Motor encoder"] end subgraph BRAIN[" "] MCU["🎮 Microcontroller
Arduino / Raspberry Pi"] Logic["🧠 Control Algorithm
• Path planning
• Obstacle detection
• PID control"] end subgraph OUTPUT[" "] Actuators["⚙️ Actuators
• DC motors
• Servos
• LEDs
• Buzzer"] end Power[("🔋 Power System
Battery & regulators")] Sensors -- "analog / digital signals" --> MCU MCU -- "sensor data" --> Logic Logic -- "control decisions" --> MCU MCU -- "PWM / GPIO commands" --> Actuators Power -. "3.3 V" .-> Sensors Power -. "5 V / 12 V" .-> MCU Power -. "12 V" .-> Actuators classDef input fill:#e3f2fd,stroke:#1976D2,stroke-width:2px classDef control fill:#fff3e0,stroke:#E65100,stroke-width:2px classDef logic fill:#f3e5f5,stroke:#6A1B9A,stroke-width:2px classDef output fill:#e8f5e9,stroke:#2E7D32,stroke-width:2px classDef power fill:#ffcdd2,stroke:#C62828,stroke-width:2px class Sensors input class MCU control class Logic logic class Actuators output class Power power
Purpose: Understand the complete data and power flow in a mechatronic system from sensing to actuation
Syllabus Link: SE-11-03, SE-11-06
Try This: Design a 3D printer system showing how sensors (temperature, position), the MCU, motors (actuators), and the nozzle (end effector) are integrated
🔌 Power, Materials and Wiring Diagrams
🎯 (SE-11-06)
📌 Determine power, battery and material requirements for mechatronic components, and Develop wiring diagrams considering data and power supply needs.
| Requirement | Engineering Detail |
|---|---|
| Power & Battery | Current Draw Calculation: Total system current is calculated by summing the individual component currents: Total Current (mA) = Σ(Component Current)🌏 Example: If a microcontroller draws 50 mA, two DC motors draw 300 mA each, and an LED draws 20 mA, total = 50 + 300 + 300 + 20 = 670 mA. A 5V supply must provide at least 670 mA capacity. Actuators often require separate power supplies from the controller to avoid "brownouts" (voltage drops) or component damage caused by the high current demands of motors. |
| Material Choice | Choosing based on weight, strength, and environmental conditions. 🌏 Example: Using carbon fibre for lightweight drone frames vs steel for industrial grippers. |
| 🛠️ Wiring Diagrams | Must utilise standard symbols (e.g., Resistor ⎓, Capacitor ╢, Motor Ⓜ). Diagrams ensure clear data and power supply documentation (SE-11-06). |
Online Tool Suggestion: Students should use Tinkercad Circuits or Wokwi to develop wiring diagrams and simulate Arduino/ESP32 hardware connections virtually before building.
♿ Specialist Requirements for People with Disability
🎯 (SE-11-05)
📌 Determine specialist requirements that influence the design and functions of mechatronic systems designed for people with disability. Inclusive design ensures that technology enhances autonomy and quality of life.
♿ Accessibility Considerations
When designing mechatronic systems for users with disabilities, engineers must consider:
🦾 Mobility Disabilities
- Prosthetics and Exoskeletons: Systems controlled by electromyography (muscle signals) or brain-computer interfaces, requiring real-time sensor fusion and responsive actuation.
- Wheelchair Automation: Systems with joystick sensitivity adjustment, voice command control, or autonomous navigation for obstacle avoidance.
👁️ Visual Impairments
- Haptic Feedback: Vibration patterns in controllers to provide tactile information instead of visual displays.
- Spatial Audio: Sound-based navigation cues to guide users around obstacles.
- Obstacle Detection: Ultrasonic or infrared sensors to alert users to hazards.
🎤 Speech and Hearing Impairments
- Visual Feedback Systems: LED indicators, screen displays for status information.
- Sign Language Recognition: Computer vision systems to interpret sign language commands.
- Text-Based Interfaces: Keyboard or touch input for users with speech difficulties.
♿ Severe Mobility Limitations
- Sip-and-Puff Control: Systems activated by gentle air pressure from the mouth for users with very limited mobility.
- Eye Gaze Tracking: Head-mounted sensors detecting where the user looks to control a cursor or robotic arm.
- Brainwave Interfaces: EEG sensors interpreting brain activity to control external devices.
Specialist requirements often add complexity and cost, but they fundamentally expand accessibility and enable people with disabilities to perform tasks they could not otherwise accomplish independently.
🧠 Algorithm Development and Control Systems
🎯 (SE-11-02)
📌 Develop, modify and apply algorithms to control a mechatronic system. Explore the algorithmic patterns, code and applications for open and closed control systems.
🔄 Open vs Closed Loop Systems
The choice of control system depends on the task requirements for accuracy and self-correction. Engineers often use 🛠️ Decision Trees (Course Spec p.10) to map out these control paths.
| System Type | Analysis / Description | Pros/Cons |
|---|---|---|
| Open Loop | Operates on a fixed sequence or timer without feedback. 🌏 Example: A sprinkler system on a timer. |
Pros: Simple, low cost. Cons: Cannot adjust to changes (e.g., if it rains). |
| Closed Loop | Uses sensor feedback to adjust output in real-time. 🌏 Example: A thermostat maintaining room temperature. |
Pros: Accurate, self-correcting. Cons: Complex, potential for instability. |
🔄 Diagram - Control Systems Comparison
Open-loop vs closed-loop feedback control
This diagram contrasts two control strategies. Open-loop systems execute commands without feedback (like a timed sprinkler), making them simple but unable to adapt. Closed-loop systems continuously sense the current state, compare it to the desired state, and adjust the output (like a thermostat), enabling accurate self-correction but requiring more complexity.
━━━━━━
COMMAND → ACTUATOR → OUTPUT
(No Feedback)
✓ Simple, fast
✗ No self-correction"/] CL["Closed Loop System
━━━━━━
SETPOINT → COMPARE → ADJUST
↓
SENSOR → FEEDBACK
✓ Accurate, adaptive
✗ Complex, slower"] OL -.->|Example| EX1["Sprinkler Timer
On at 6am, Off at 6:30am
(Ignores rain)"] CL -.->|Example| EX2["Thermostat
Maintains 22°C
Adjusts heater based on
temperature feedback"] style OL fill:#E3F2FD,stroke:#1976D2,stroke-width:2px style CL fill:#C8E6C9,stroke:#2E7D32,stroke-width:2px style EX1 fill:#FFF9C4,stroke:#F57F17,stroke-width:1px style EX2 fill:#FFF9C4,stroke:#F57F17,stroke-width:1px
Purpose: Visually compare open and closed loop control systems. Open loop executes a fixed sequence; closed loop continuously adjusts based on feedback. The choice depends on accuracy requirements and environmental variability.
Syllabus Link: SE-11-02
Try This: Design a closed loop temperature control system for a greenhouse. What sensor would you use? What setpoint? How would the system respond if external temperature drops?
🤖 Features of Autonomous Control Algorithms
🎯 (SE-11-02)
📌 Outline the features of an algorithm and program code used for autonomous control. Autonomous systems must make decisions independently, handle sensor data, and adapt to environmental changes.
🤖 Key Features of Autonomous Algorithms
- 🔗 Sensor Fusion: Combining data from multiple sensors (e.g., distance sensors, IMU accelerometers, temperature sensors) to build a comprehensive understanding of the environment. Simple algorithms average sensor readings; advanced algorithms use Kalman filters for optimal estimation.
- 🧠 Decision Logic: Complex conditionals and state machines that determine what action to take based on current sensor readings and system state. Example: "IF obstacle detected within 20cm AND left sensor clear, TURN LEFT; ELSE IF right sensor clear, TURN RIGHT."
- 🔄 PID Control Loop: Proportional-Integral-Derivative control adjusts actuator output based on error (difference between desired and actual state). Common in maintaining speed, temperature, or position.
- 📊 State Management: Tracking the current state of the system (idle, moving, gripper_open, gripper_closed) and transitioning between states safely based on sensor feedback and logic.
- ⚡ Real-Time Response: Meeting strict timing requirements—responding to sensors and issuing commands within specified time windows. Delays in real-time systems can cause crashes or safety failures.
- 🛡️ Fallback Safety Logic: Default safe states (e.g., "all motors stop" if communication is lost) to prevent uncontrolled operation.
Autonomous algorithms typically use flowcharts, state diagrams, and pseudocode to be designed clearly before implementation. Testing autonomous systems requires extensive simulation and careful incremental real-world validation.
🚦 State Diagram - Traffic Light FSM
State transitions with emergency override logic
This state diagram shows how a traffic light operates as a finite state machine with three states (RED, YELLOW, GREEN). Transitions occur based on timer conditions (30 seconds per state). The emergency override demonstrates responsive systems: when an emergency vehicle is detected, all lights transition to RED immediately, overriding normal timing.
Purpose: Model a traffic light control system as a state machine showing state transitions, timers, and emergency override capability
Syllabus Link: SE-11-02
Try This: Add a fourth state "PEDESTRIAN_CROSSING" that transitions from YELLOW and extends the RED duration, then code this logic in Arduino
💻 Design, Develop and Produce a Mechatronic System
🎯 (SE-11-01, SE-11-02, SE-11-05, SE-11-06, SE-11-07)
📌 Design, develop and produce a mechatronic system for a real-world problem, integrating software control, mechanical engineering, electronics and mathematics.
🧩 Integrated System Design
Creating a complete mechatronic system requires simultaneous consideration of three domains:
⚙️ Software Control
Algorithms and code that orchestrate sensor input, decision logic, and actuator output. Must be reliable, efficient, and responsive.
🦾 Mechanical Engineering
The physical structure, joints, materials, and mechanisms. Must support the required range of motion, handle the forces generated, and integrate smoothly with electronics.
🔌 Electronics and Mathematics
Power circuits, signal conditioning, control mathematics (PID tuning), and sensor calibration. Requires understanding electrical properties of components and mathematical models of system behaviour.
Success requires communication and iteration between all three disciplines. For example, software delays might come from inadequate motor response, which is a mechanical/control issue; noise in sensor readings might require better filtering (electrical) or algorithm adjustments (software).
🔧 Implementation and Integration
🎯 (SE-11-05, SE-11-06)
📌 Implement algorithms and design programming code to drive mechatronic devices. Apply programming to integrate sensors, actuators and end effectors. Implement specific control algorithms for performance enhancement.
🏎️ Driving Mechatronic Devices
Code must correctly interface with hardware:
- PWM (Pulse Width Modulation): Varying the duty cycle (on-time vs off-time) of a square wave to control motor speed or LED brightness.
- Analog-to-Digital Conversion: Reading analog sensor values (e.g., 0-5V) as digital numbers (0-1023) for processing.
- Serial Communication: Sending commands to and receiving data from sensors, actuators, and other microcontrollers.
- Interrupt Handling: Responding immediately to urgent events (e.g., collision detection) without waiting for the main program loop.
🔌 Integrating Components into Viable Subsystems
Each subsystem (gripper, movement, vision) must be coded, tested, and debugged in isolation before integration. Components share power supplies, communication buses, and may have timing dependencies—careful integration prevents conflicts.
⚡ Control Algorithm Optimisation
Specific algorithms enhance performance:
- PID Tuning: Adjusting proportional, integral, and derivative gains to achieve fast, stable response without overshoot.
- Acceleration Ramping: Gradually increasing motor speed to reduce jerky movements and mechanical stress.
- Sensor Filtering: Averaging or smoothing noisy sensor readings to improve decision quality.
🧪 Prototyping, Simulation and Testing
🎯 (SE-11-06, SE-11-07)
📌 Develop simulations and prototypes to test programming code. Design and implement closed loop control systems. Design and develop a user interface. Create and use unit tests for effectiveness and repeatability.
🧪 Simulation vs Prototyping
Simulations (Wokwi, TinkerCAD, Gazebo) allow testing code in a risk-free virtual environment. Useful for debugging algorithms, testing edge cases, and exploring design variations before building hardware. However, simulations don't capture real-world issues like friction, vibration, electromagnetic interference, or component tolerances.
Physical prototypes identify these real-world factors. Starting with a minimal viable prototype (MVP) and iteratively improving it is more cost-effective than building a perfect system immediately. Prototyping also allows testing with actual users and refining the design based on their feedback.
🔄 Closed Loop Control System Design and Implementation
Closed loop systems use sensor feedback to adjust actuator output continuously. Implementation requires:
- Clearly defining the setpoint (desired state) and feedback (actual state).
- Calculating the error (setpoint - feedback).
- Applying a control algorithm (PID, fuzzy logic, state machine) to generate corrective output.
- Iterating: reading sensors, calculating, and updating actuators in a tight loop (typically 10-1000 Hz).
🖥️ User Interface (UI) Design and Implementation
Even autonomous systems often need interfaces for:
- Manual Override: Emergency stop buttons, mode selection switches.
- Status Display: LED indicators, LCD screens showing system state, error codes, sensor readings.
- Configuration: Buttons to set parameters (speed, sensitivity, operating mode).
- Accessibility: Voice control, touchless interfaces for users with disabilities.
UI code must be responsive and not interfere with real-time control loops. Separating UI from control logic (Model-View-Controller pattern) improves maintainability.
🧪 Unit Testing for Effectiveness and Repeatability
Mechatronic systems require rigorous testing of each component:
- Sensor Tests: Verify sensors return expected values for known inputs (temperature sensor in ice vs boiling water).
- Actuator Tests: Confirm motors respond correctly to commands (PWM 50% = half speed).
- Algorithm Tests: Verify logic produces correct outputs (e.g., a collision avoidance routine turns away from obstacles).
- Integration Tests: Test subsystems working together (e.g., vision detects object + gripper activates + movement ceases).
- Stress Tests: Run systems continuously for extended periods to identify degradation or reliability issues.
Repeatability testing ensures the system behaves consistently across multiple trials—critical for autonomous systems where unpredictable behaviour is unacceptable. Logging sensor data and actuator commands during tests helps engineers debug failures and improve reliability.
⚡ Interrupts & Interrupt Service Routines (ISRs)
🎯 (SE-11-05, SE-11-06)
📌 Describe hardware and software interrupts and apply ISRs to build responsive mechatronic systems that react instantly to events.
⚡ What is an Interrupt?
An interrupt is a signal that causes the CPU to pause its current task, execute a special handler routine (the ISR), and then resume where it left off. Without interrupts, the CPU must constantly check (poll) whether an event has occurred — wasting cycles and potentially missing fast events.
⚙️ Hardware Interrupts
Generated by external hardware events — a button press, a timer overflow, a serial byte arriving, or a sensor threshold crossing. These are signal-level events on specific microcontroller pins.
💾 Software Interrupts
Triggered deliberately by software (e.g., via an INT instruction or OS system call). Used for exception handling, context switching in an RTOS, and calling OS services.
⚖️ Polling vs Interrupts
| Aspect | Polling | Interrupts |
|---|---|---|
| Response time | Delayed — depends on loop frequency | Immediate — CPU pauses instantly |
| CPU usage | High — CPU spins checking constantly | Low — CPU only acts when needed |
| Code complexity | Simple — just a loop with an if check | Moderate — requires ISR and shared variables |
| Best for | Slow events, simple programs | Fast events, real-time requirements |
📜 ISR Rules — Keep Them Short!
✓ Keep ISRs as short as possible — set a flag and return; do the heavy work in the main loop.
✓ Never call
time.sleep(), print(), or blocking I/O inside an ISR.✓ Use
volatile variables (or ensure visibility) for data shared between ISR and main code.✓ Disable interrupts around critical sections when reading multi-byte values updated by an ISR.
from machine import Pin
import time
button_pressed = False # Flag shared with ISR
def button_isr(pin):
global button_pressed
button_pressed = True # Set flag — don't do work here
button = Pin(14, Pin.IN, Pin.PULL_UP)
button.irq(trigger=Pin.IRQ_FALLING, handler=button_isr)
# Main loop
while True:
if button_pressed:
button_pressed = False # Clear the flag
print("Button was pressed!")
time.sleep_ms(10)
volatile bool buttonPressed = false; // volatile: tells compiler not to optimise away
void buttonISR() {
buttonPressed = true; // Set flag only — no Serial.print here!
}
void setup() {
Serial.begin(9600);
pinMode(2, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(2), buttonISR, FALLING);
}
void loop() {
if (buttonPressed) {
buttonPressed = false;
Serial.println("Button pressed!");
}
delay(10);
}
🆚 Arduino C vs MicroPython
🎯 (SE-11-05)
📌 Compare Arduino C and MicroPython for mechatronic programming — understanding the trade-offs helps you select the right language for each task.
⚖️ Side-by-Side Comparison
| Feature | Arduino C | MicroPython |
|---|---|---|
| Language base | C/C++ (compiled) | Python 3 (interpreted) |
| Memory usage | Very low — compiled binary | Higher — interpreter overhead |
| Execution speed | Fast — direct machine code | Slower — bytecode interpreted |
| IDE | Arduino IDE, PlatformIO | Thonny, VS Code + Pymakr |
| Library ecosystem | Vast (thousands of libraries) | Growing (smaller but capable) |
| Ease of learning | Harder — C syntax, manual memory | Easier — clean Python syntax |
| Real-time capability | Excellent — deterministic timing | Limited — GC pauses possible |
| Boards | Arduino Uno/Nano/Mega, ESP32 | Raspberry Pi Pico, ESP32, ESP8266 |
void setup() {
pinMode(LED_BUILTIN, OUTPUT); // setup() runs once at power-on
}
void loop() {
digitalWrite(LED_BUILTIN, HIGH); // loop() repeats forever
delay(500);
digitalWrite(LED_BUILTIN, LOW);
delay(500);
}
from machine import Pin
import time
led = Pin(25, Pin.OUT) # GPIO 25 = onboard LED on Pico
while True:
led.toggle()
time.sleep(0.5)
Choose Arduino C when: you need precise timing, low latency, real-time control (PID loops, stepper motors at high speed), or must support a specific hardware library only available in C.
Choose MicroPython when: you want rapid prototyping, easy debugging via REPL, and your control loop doesn't need sub-millisecond timing. Great for HSC projects.
📡 Communication Protocols
🎯 (SE-11-05, SE-11-06)
📌 Describe I2C, SPI, and UART communication protocols and apply them to connect sensors and peripherals to microcontrollers.
🔗 I2C (Inter-Integrated Circuit)
I2C uses two wires (SDA — data, SCL — clock) and supports multiple devices on the same bus using unique 7-bit addresses. A single master controller communicates with one or more slaves.
📋 I2C Key Facts
- 2 wires: SDA (data) + SCL (clock)
- Up to 127 devices per bus (7-bit addressing)
- Speed: 100 kHz (standard), 400 kHz (fast)
- Typical devices: OLED displays, BME280, MPU6050
from machine import I2C, Pin
i2c = I2C(0, scl=Pin(1), sda=Pin(0), freq=400000)
devices = i2c.scan()
print("I2C devices found:", [hex(d) for d in devices])
# e.g. I2C devices found: ['0x76', '0x3c']
🔗 SPI (Serial Peripheral Interface)
SPI uses four wires (MOSI, MISO, SCK, CS) and is faster than I2C. Each device needs its own CS (Chip Select) wire.
📡 UART (Universal Asynchronous Receiver-Transmitter)
UART uses two wires (TX, RX) and needs no clock signal — both devices must agree on the same baud rate (bits per second). Common for GPS modules, Bluetooth HC-05, and USB-serial bridges.
from machine import UART
import time
uart = UART(1, baudrate=9600, tx=4, rx=5)
while True:
if uart.any():
data = uart.readline()
if data:
print(data.decode('utf-8', 'ignore').strip())
⚖️ Protocol Comparison
| Protocol | Wires | Speed | Multiple devices? | Typical devices |
|---|---|---|---|---|
| I2C | 2 (SDA + SCL) | Up to 400 kHz | Yes — by address | Sensors, displays, RTCs |
| SPI | 4 (MOSI+MISO+SCK+CS) | Up to 80 MHz | Yes — separate CS per device | SD cards, displays, ADCs |
| UART | 2 (TX + RX) | 9600–115200 baud | No — point-to-point | GPS, Bluetooth, USB-serial |
🔩 Motor Control
🎯 (SE-11-05, SE-11-06)
📌 Apply programming techniques to control DC motors, servo motors, and stepper motors in mechatronic systems.
🏎️ DC Motors
DC motors spin continuously. Speed is controlled by PWM duty cycle and direction by reversing current flow through an H-bridge circuit.
H-Bridge (L298N) — 4 switches control direction
───────────────────────────────────────────────
+V ──┬───── S1 ─────┬───── S3 ──── +V
│ │
Motor A Motor B
│ │
GND ──┴───── S2 ─────┴───── S4 ──── GND
S1+S4 closed → motor spins FORWARD
S2+S3 closed → motor spins REVERSE
All open → motor coasts (no brake)
PWM and speed: The duty cycle of the PWM signal controls how much average voltage reaches the motor:
- 0% duty cycle → motor stopped (0 V average)
- 50% duty cycle → half speed (~half voltage)
- 100% duty cycle → full speed (full voltage)
from machine import Pin, PWM
import time
# L298N pin connections
IN1 = Pin(2, Pin.OUT)
IN2 = Pin(3, Pin.OUT)
ENA = PWM(Pin(4))
ENA.freq(1000) # 1 kHz PWM frequency
def motor_forward(speed):
"""speed: 0-100 (percent)"""
IN1.value(1)
IN2.value(0)
ENA.duty_u16(int(speed / 100 * 65535))
def motor_reverse(speed):
IN1.value(0)
IN2.value(1)
ENA.duty_u16(int(speed / 100 * 65535))
def motor_stop():
IN1.value(0)
IN2.value(0)
ENA.duty_u16(0)
motor_forward(75) # 75% speed forward
time.sleep(2)
motor_reverse(50) # 50% speed reverse
time.sleep(2)
motor_stop()
🦾 Servo Motors
Servo motors rotate to a specific angle (0–180°). They are controlled by a PWM signal where pulse width determines position: ~1 ms = 0°, ~1.5 ms = 90°, ~2 ms = 180°.
from machine import Pin, PWM
import time
servo = PWM(Pin(15))
servo.freq(50) # Servos require 50 Hz (20 ms period)
def set_angle(angle):
"""Set servo to angle (0-180 degrees)"""
# Map 0-180° to pulse width 1000-2000 µs
# duty_u16 range 0-65535 maps to 0-20ms
min_duty = int(1000 / 20000 * 65535) # 1 ms → 0°
max_duty = int(2000 / 20000 * 65535) # 2 ms → 180°
duty = int(min_duty + (angle / 180) * (max_duty - min_duty))
servo.duty_u16(duty)
set_angle(0)
time.sleep(1)
set_angle(90)
time.sleep(1)
set_angle(180)
🏎️ DC Motor: Variable speed, continuous rotation — robots, fans, conveyor belts.
🦾 Servo Motor: Precise angle control, self-holding — robotic arms, steering, camera gimbals.
🔩 Stepper Motor: Discrete steps, no feedback needed — 3D printers, CNC machines, precision positioning.
🐛 Hardware Debugging
🎯 (SE-11-06, SE-11-07)
📌 Apply systematic debugging techniques to identify and resolve faults in mechatronic hardware and software.
🐛 Debugging Tools
print() liberally during development.Common Hardware Faults
| Symptom | Likely Cause | Fix |
|---|---|---|
| Nothing powers on | Loose power connection or wrong voltage | Check voltage with multimeter, re-seat connections |
| Sensor always reads 0 | Wrong pin, incorrect pull-up/down, sensor not powered | Check wiring diagram, verify sensor VCC |
| Sensor reads very noisy values | Long wires acting as antenna, no decoupling capacitor | Add 100nF capacitor near sensor, shorten wires |
| Motor spins wrong direction | H-bridge IN1/IN2 reversed | Swap IN1 and IN2 in code or swap motor wires |
| I2C device not found | Wrong address, SDA/SCL swapped, missing pull-ups | Run I2C scan, check datasheet for address, add 4.7k pull-ups |
| Code hangs after a few seconds | Infinite loop in ISR, watchdog timer, stack overflow | Check ISR length, enable REPL to inspect state |
Systematic Debugging Process
Systematic Hardware Debugging
──────────────────────────────────────────────────────
1. OBSERVE → Describe the symptom precisely
("motor runs backwards at full speed")
│
2. ISOLATE → Test components independently
(test motor alone, then H-bridge, then code)
│
3. HYPOTHESISE → What could cause this? List 3 possibilities
(wrong pin, wrong polarity, bad driver)
│
4. TEST → Change ONE variable at a time
(swap only IN1/IN2, then re-test)
│
5. VERIFY → Confirm the fix works consistently
(run 10 times, check corner cases)
│
6. DOCUMENT → Record the fault and fix in your process diary
──────────────────────────────────────────────────────