A410 of 56
0 XP
  1. Hook
  2. Predict
  3. Name it
  4. Check
  5. Explain

A4 · Lesson 10 · Lab: decisions, loops and functions

Picking parts, running a thermostat and timing an oscillator in code

Lessons 7 to 9 gave you if, loops and functions with defaults and function arguments. On their own they're small; together they're most of what everyday engineering code does. This lab uses them on four jobs: choosing a real resistor and its power rating, running a thermostat over a day of temperatures, timing a relaxation oscillator step by step, and finding where a filter's gain falls to a given level by searching with a function you pass in.

Predict

A loop adds 0.001 to v two thousand times, starting from 0. Does v >= 2.0 come out True?

Name it

Patterns this lab uses

  • Search a list with a condition: min(v for v in values if v >= target) finds the smallest value that's big enough.
  • A loop with state: keep the variables that carry over (a voltage, whether a heater is on) outside the loop, and update them each pass.
  • Count events: an if inside the loop increments a counter or appends an index when something happens.
  • Pass a function in: a search written once, bisect(f, a, b), works for any f, and a lambda builds a small f on the spot.
  • Defaults for the usual case: sweep(start, stop, n=10, log=False) gives the common call a short form and the unusual one a keyword.

Worked example

An LED drops 2.0 V and should run at no more than 15 mA from a 5 V supply. Choose the E12 resistor and its power rating, using a rating at least twice the dissipation.

Show the solution
  1. Find the ideal resistance. R=5−2.00.015Ω=200Ω
  2. Search the E12 values and the ratings. Take the smallest E12 value at or above the ideal, then the smallest rating at least twice the dissipation.
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]
values = [m * 10**d for d in range(7) for m in E12]
ideal = (5 - 2.0) / 0.015                        # 200 Ω
R = min(v for v in values if v >= ideal - 1e-9)  # 220 Ω
I = (5 - 2.0) / R                                # 13.6 mA
P = I**2 * R                                     # 0.0409 W
rating = min(r for r in [0.125, 0.25, 0.5, 1] if r >= 2 * P)
print(R, I, P, rating)                           # 220.0 0.01364 0.0409 0.125
  1. Round up to E12. The ideal 200 Ω isn't an E12 value, so the next one up, 220 Ω, keeps the current under the limit: I=3V220Ω=13.6mA
  2. Choose the rating. It dissipates 41 mW, and twice that fits in the smallest common rating, 1/8 W.
  3. Guard the comparison. The - 1e-9 guards against an E12 value computed as 149.99999999 being skipped when the ideal is exactly 150.

Answer a 220 Ω resistor rated 1/8 W, which runs the LED at 13.6 mA.

Worked example

A 10 µA current source charges 100 nF. When the voltage reaches 2.0 V a comparator discharges it to zero at once. Simulate 100 ms in 10 µs steps and measure the period.

Show the solution
  1. Step the charge and record each reset. Each step adds IΔt/C = 1 mV, and the comparator zeroes the voltage at 2.0 V.
C, I, Vth, dt = 100e-9, 10e-6, 2.0, 10e-6
v, resets = 0.0, []
for k in range(10000):
    v += I * dt / C              # 1 mV per step
    if v >= Vth:
        v = 0.0
        resets.append(k)
period = (resets[-1] - resets[0]) / (len(resets) - 1) * dt
print(len(resets), period)       # 4 0.02001
  1. Compare with the formula. T=CVthI=(100nF)(2.0V)10μA=20ms and the simulation gives 20.01 ms.
  2. Explain the extra step. The simulation takes 2001 steps per cycle instead of 2000, because two thousand additions of 0.001 land just short of 2.0.
  3. Judge the error. It is one time step, which is the most a stepped simulation can be trusted to resolve an event's time anyway.

Answer the simulated period is 20.01 ms, one 10 µs step longer than the 20 ms the formula gives.

Check

Write led(Vs, Vf, I_max) returning (R, rating): the smallest E12 resistor (from the starter's values) that keeps the current at or below I_max amps, and the smallest of 0.125, 0.25, 0.5 and 1 W that's at least twice its dissipation. Then set R, rating = led(Vs, Vf, I / 1000) for Vs = 5 V, Vf = 1.8 V and I = 20 mA.

Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.

Check

The starter makes temps, a day of room temperatures, one per minute. A thermostat turns the heater on when the temperature is below lo = 19 °C and off when it's above lo + band (1 °C higher), and otherwise leaves it as it was. Starting with the heater off, set on to a list of the heater's state each minute, switches to how many times it changed, and duty to the fraction of minutes it was on.

Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.

Check

A current source of Ic = 10 µA charges C = 47 nF until the voltage reaches Vth = 3 V, when it's discharged to zero at once. Simulate 0.5 s in steps of 10 µs. Set n to the number of discharges, period to the average spacing between them in seconds, and ideal to CVth/I.

Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.

Check

Write bisect(f, a, b, tol=1e-9), which halves [a, b] until it's narrower than tol times b and returns its midpoint (assume f(a) and f(b) have opposite signs). Use it with a lambda to set f to the frequency, between 1 Hz and 100 MHz, where an RC low-pass with corner fc = 1000 Hz has gain g = 0.5: the gain is 1/1+(f/fc)2.

Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.

Check

Write sweep(start, stop, n=10, log=False) returning a list of n values from start to stop inclusive: evenly spaced, or with equal ratios between neighbors when log=True. Then set lin = sweep(a, b, n) and geo = sweep(a, b, n, log=True) for a = 10, b = 1000 and n = 11.

Python 3.14 with numpy and matplotlib, running in your browser. Tab indents; press Esc and then Tab to move on.

Check

A 5 µA current source charges 100 nF from 0 V. How long until the capacitor reaches 3 V?

Write units the way you normally would: 1.5 s and 1500 ms are the same answer.

Explain why

In the thermostat, why does the heater's state have to be kept outside the loop, while the temperature doesn't?

Practice

Keep practicing

6 kinds of problem on this topic, dealt one at a time with new numbers every time, for as long as you like.