Project 11: Power Budget and Battery Runtime Tracker

Measure voltage/current, compute power, and estimate battery runtime under different workloads.

Quick Reference

Attribute Value
Difficulty Advanced
Time Estimate 1–2 weekends
Main Programming Language Python (Alternatives: C, Go, Rust)
Alternative Programming Languages C, Go, Rust
Coolness Level High
Business Potential High
Prerequisites I2C basics, multimeter use, sensor wiring
Key Topics Power measurement, battery discharge curves, runtime estimation

1. Learning Objectives

By completing this project, you will:

  1. Measure voltage and current using a power sensor.
  2. Calculate real-time power and energy consumption.
  3. Estimate battery runtime using smoothed data.
  4. Evaluate how workloads change power draw.

2. All Theory Needed (Per-Concept Breakdown)

Concept 1: Power Measurement and Runtime Estimation

Fundamentals

Power is the product of voltage and current (P = V × I). To estimate battery runtime, you must measure current draw over time and relate it to battery capacity. Batteries are rated in milliamp-hours (mAh), but real runtime depends on discharge curves, load, and efficiency losses. Using a power sensor (e.g., INA219) on I2C, you can measure current and voltage, then compute power. The core of this project is turning raw electrical measurements into practical runtime estimates.

Deep Dive into the concept

Power measurement on embedded systems is usually done with a shunt resistor and a measurement IC. A device like the INA219 measures the voltage drop across a shunt and calculates current. It also measures bus voltage. From these, you compute power and energy. The measurements are not perfect; they have noise, offset, and quantization. This is why smoothing (moving average or exponential smoothing) is essential for stable estimates.

Battery capacity in mAh is measured at a specific discharge rate, often 0.2C. When you draw more current, the effective capacity drops due to internal resistance and chemistry. This means runtime is not simply capacity divided by current. A realistic model needs at least a correction factor or an empirically measured discharge curve. For this project, you can implement a simplified model: runtime_hours = capacity_mAh / current_mA * efficiency. The efficiency factor (e.g., 0.8) accounts for losses in voltage regulation and battery behavior. You should calibrate this factor by running a partial discharge test.

Workloads matter. Wi-Fi, CPU load, camera usage, and USB devices each add a measurable current increase. A robust power budget tool should allow you to label workload modes and compare current consumption across modes. For example, idle might be 250 mA, Wi-Fi scanning 350 mA, and camera capture 500 mA. Recording these deltas helps you design a runtime budget and choose a battery size.

Measurement cadence is another factor. If you sample too slowly, you miss spikes; too fast, and you create noise and overhead. A typical interval is 1–5 seconds with smoothing. For runtime estimation, you want stable averages rather than instantaneous spikes. You should also detect and log undervoltage events or sudden drops, which indicate power instability or battery near depletion.

Finally, the output must be meaningful. A runtime estimate should include a confidence range and update slowly, not jump on every measurement. This can be done by smoothing the current and limiting how quickly the estimate changes. A daily power log is also valuable for long-term analysis.

How this fit on projects

This concept is used in §3, §4, and §5.10. It feeds directly into the capstone project where battery runtime is critical.

Definitions & key terms

  • Shunt resistor: Low-value resistor used for current measurement.
  • mAh: Milliamp-hour battery capacity.
  • C-rate: Discharge rate relative to capacity.
  • Exponential smoothing: Weighted average giving more weight to recent samples.

Mental model diagram (ASCII)

Battery -> Shunt -> Sensor -> I2C -> Power Log -> Runtime Estimate

How it works (step-by-step, with invariants and failure modes)

  1. Read voltage and current from sensor.
  2. Compute power and log values.
  3. Smooth current and estimate runtime.
  4. Detect anomalies (spikes, undervoltage).

Failure modes:

  • Wrong shunt value -> incorrect current.
  • I2C errors -> missing data.
  • No smoothing -> unstable estimates.

Minimal concrete example

power_w = voltage_v * current_a
runtime_h = (capacity_mAh / current_mA) * 0.8

Common misconceptions

  • “mAh directly equals runtime.” It depends on load.
  • “Instant current equals average.” It needs smoothing.

Check-your-understanding questions

  1. Why does battery capacity depend on discharge rate?
  2. How does a shunt resistor measure current?
  3. Why is smoothing required for runtime estimates?

Check-your-understanding answers

  1. Higher discharge reduces usable capacity.
  2. The sensor measures voltage drop across the shunt.
  3. Raw current values fluctuate and cause unstable estimates.

Real-world applications

  • Battery-powered IoT devices and field sensors.

Where you’ll apply it

  • This project: §3.2, §5.10.
  • Other projects: Project 17.

References

  • INA219 datasheet
  • “Making Embedded Systems” — power management

Key insights

Runtime estimation is a modeling problem, not just a measurement problem.

Summary

A power tracker turns electrical measurements into actionable runtime predictions.

Homework/Exercises to practice the concept

  1. Measure idle current and compute runtime.
  2. Compare runtime estimates with actual battery discharge.
  3. Plot current over time with Wi-Fi on/off.

Solutions to the homework/exercises

  1. Use INA219 readings and compute runtime.
  2. Adjust efficiency factor based on test results.
  3. Wi-Fi increases current; document the delta.

3. Project Specification

3.1 What You Will Build

A power monitor that logs voltage/current and estimates battery runtime across workload modes.

3.2 Functional Requirements

  1. Read voltage and current from power sensor.
  2. Compute power and log data.
  3. Estimate runtime with smoothing.
  4. Compare power draw across workloads.

3.3 Non-Functional Requirements

  • Performance: Sample interval 1–5s.
  • Reliability: Sensor reads succeed >99%.
  • Usability: Logs are clear and exportable.

3.4 Example Usage / Output

$ ./power_tracker
Voltage: 5.08 V  Current: 320 mA  Power: 1.63 W
Estimated runtime: 4h 12m

3.5 Data Formats / Schemas / Protocols

CSV log:

2026-01-01T11:45:00Z,5.08,0.320,1.63

3.6 Edge Cases

  • Sensor not detected.
  • Sudden current spikes.
  • Battery voltage drop below threshold.

3.7 Real World Outcome

Runtime estimates track real battery performance and update smoothly.

3.7.1 How to Run (Copy/Paste)

python3 power_tracker.py --capacity 5000 --interval 2

3.7.2 Golden Path Demo (Deterministic)

export FIXED_TIME="2026-01-01T11:45:00Z"
python3 power_tracker.py --simulate --current 0.32 --voltage 5.08

Expected output:

[2026-01-01T11:45:00Z] Runtime: 4h12m

3.7.3 Failure Demo (Deterministic)

python3 power_tracker.py --simulate --sensor-missing

Expected output:

[ERROR] Power sensor not detected

Exit code: 111

3.7.4 CLI Exit Codes

  • 0: Success
  • 110: I2C init failure
  • 111: Sensor missing

4. Solution Architecture

4.1 High-Level Design

Sensor -> Measurement -> Smoothing -> Runtime Estimate -> Logger

4.2 Key Components

| Component | Responsibility | Key Decisions | |—|—|—| | Sensor Reader | Read V/I | I2C address | | Calculator | Compute power | Units | | Smoother | Stabilize data | EMA vs moving avg | | Reporter | Format output | CSV vs JSON |

4.3 Data Structures (No Full Code)

ema_current = alpha * current + (1-alpha) * ema_current

4.4 Algorithm Overview

Key Algorithm: EMA Smoothing

  1. Read current.
  2. Update exponential average.
  3. Estimate runtime from smoothed current.

Complexity Analysis:

  • Time: O(1)
  • Space: O(1)

5. Implementation Guide

5.1 Development Environment Setup

sudo apt-get install -y python3-smbus i2c-tools

5.2 Project Structure

project-root/
├── power_tracker.py
├── smoothing.py
└── README.md

5.3 The Core Question You’re Answering

“How do you predict real battery life instead of guessing?”

5.4 Concepts You Must Understand First

  1. Power math (V × I).
  2. Battery capacity vs real runtime.
  3. Smoothing and sampling.

5.5 Questions to Guide Your Design

  1. What workloads represent worst-case power draw?
  2. How will you smooth runtime estimates?

5.6 Thinking Exercise

Compute runtime for 5000mAh battery at 350mA draw.

5.7 The Interview Questions They’ll Ask

  1. Why is battery capacity not equal to runtime?
  2. How do you measure current safely?
  3. How do you reduce power in software?

5.8 Hints in Layers

Hint 1: Measure idle current first.

Hint 2: Add Wi-Fi and compare deltas.

Hint 3: Smooth estimates to reduce jumps.

5.9 Books That Will Help

| Topic | Book | Chapter | |—|—|—| | Power fundamentals | Practical Electronics for Inventors | Ch. 2 | | Embedded power | Making Embedded Systems | Ch. 8 |

5.10 Implementation Phases

Phase 1: Sensor Setup (3 hours)

  • Verify I2C sensor reads.

Phase 2: Calculation (4 hours)

  • Compute power and runtime.

Phase 3: Workload profiling (4 hours)

  • Measure idle, Wi-Fi, camera loads.

5.11 Key Implementation Decisions

| Decision | Options | Recommendation | Rationale | |—|—|—|—| | Smoothing | Moving avg / EMA | EMA | Simple and responsive | | Logging | CSV / JSON | CSV | Easy plotting |


6. Testing Strategy

6.1 Test Categories

| Category | Purpose | Examples | |—|—|—| | Unit Tests | Power math | V*I calculation | | Integration Tests | Sensor read | INA219 live | | Edge Case Tests | Missing sensor | Exit 111 |

6.2 Critical Test Cases

  1. Correct runtime estimate for fixed current.
  2. Sensor missing -> exit code 111.
  3. Runtime estimate changes smoothly.

6.3 Test Data

Voltage=5.08V, Current=0.32A

7. Common Pitfalls & Debugging

7.1 Frequent Mistakes

| Pitfall | Symptom | Solution | |—|—|—| | Wrong shunt value | Incorrect current | Configure sensor correctly | | No smoothing | Jumping estimates | Use EMA | | Bad wiring | Zero readings | Check SDA/SCL |

7.2 Debugging Strategies

  • Use multimeter to validate sensor readings.
  • Plot data to visualize noise.

7.3 Performance Traps

  • Sampling too frequently increases CPU load.

8. Extensions & Challenges

8.1 Beginner Extensions

  • Add battery percentage estimate.

8.2 Intermediate Extensions

  • Plot live power chart with ASCII graph.

8.3 Advanced Extensions

  • Implement Peukert’s law correction.

9. Real-World Connections

9.1 Industry Applications

  • Battery-powered IoT and remote sensors.
  • ina219 Python library.

9.3 Interview Relevance

  • Power budgeting is a common embedded interview topic.

10. Resources

10.1 Essential Reading

  • INA219 datasheet and app notes.

10.2 Video Resources

  • Battery measurement tutorials.

10.3 Tools & Documentation

  • i2cdetect and INA219 docs.

11. Self-Assessment Checklist

11.1 Understanding

  • I can explain how shunt-based current measurement works.
  • I can explain runtime estimation assumptions.

11.2 Implementation

  • Power readings are stable.
  • Runtime estimates respond smoothly to load changes.

11.3 Growth

  • I can discuss power budgeting in interviews.

12. Submission / Completion Criteria

Minimum Viable Completion:

  • Current and voltage logged once per second.

Full Completion:

  • Runtime estimate and workload comparisons.

Excellence (Going Above & Beyond):

  • Discharge curve model and battery health estimates.