# Tactiverge Academy — companion code for "Power, series and parallel circuits"
# Lesson: https://tactiverge.win/academy/embedded-systems/digital-electronics-fundamentals/power-series-and-parallel/
# Licence: MIT (see https://tactiverge.win/open-engineering/). Examples appear in lesson order.

# ── Example 1 ────────────────────────────────────────
E12 = [1.0, 1.2, 1.5, 1.8, 2.2, 2.7, 3.3, 3.9, 4.7, 5.6, 6.8, 8.2]

def next_standard(r):
    """Smallest E12 resistor value that is at least r ohms."""
    decade = 1.0
    while True:
        for base in E12:
            if base * decade >= r:
                return base * decade
        decade *= 10

def led_resistor(supply_v, led_v, target_ma):
    exact = (supply_v - led_v) / (target_ma / 1000)
    chosen = next_standard(exact)
    current_ma = (supply_v - led_v) / chosen * 1000
    power_mw = (supply_v - led_v) * current_ma
    return exact, chosen, current_ma, power_mw

for supply in (5.0, 3.3):
    exact, chosen, i, p = led_resistor(supply, 2.0, 10)
    print(f"{supply} V: exact {exact:.0f} ohm, use {chosen:.0f} ohm, "
          f"current {i:.1f} mA, resistor power {p:.0f} mW")
