Schematics, Active-Low Circuits, and Register Maps
Start from CMOS output transistors and Kirchhoff's Voltage Law to understand why active-low LEDs illuminate when a GPIO sinks current to ground, trace schematic nets across board-to-board connectors to i.MX6ULL ball GPIO1_IO03, and update single register bits safely in ISO C11.
What you'll learn
- Trace a carrier net through a core connector to its SoC pad.
- Derive active-low output behavior from an LED current path.
- Calculate register addresses and masks without altering sibling pins.
CMOS Push-Pull Pads, Active-Low Sinking, and Kirchhoff Current Loops
Beginners often assume "writing 1 to a GPIO pin turns an LED on, and writing 0 turns it off." On industrial ARM boards, writing 1 frequently turns the LED off, and writing 0 turns it brightly on! Why? Because a GPIO pin is not a magic software boolean—it is a pair of physical complementary MOSFET switches (CMOS) wired between the pad's I/O supply rail (NVCC_GPIO = 3.30 V) and board ground (GND = 0 V). Look inside the pad stage in Figure 1.3a:
- High-Side
PMOSSource (DR = 1): Connects the package ball up to3.30 V(V_OH). If an external load runs from the pin through a resistor and LED toGND(active-high source topology, right panel), current flows out of thePMOStransistor into the LED whenDR = 1. - Low-Side
NMOSSink (DR = 0): Connects the package ball down toGNDwith a small transistor drop (V_OL = 0.15 V = 150 mV). On most carrier boards (active-low sink topology, left panel), the hardware designer wires3.30 V -> R (1000 ohm) -> LED Anode | Cathode -> GPIO1_IO03. WhenDR[3] = 1, both ends of the LED+resistor branch sit near3.30 V(0 Vpotential difference -> zero current -> LED dark!). WhenDR[3] = 0, theNMOSswitch closes toGND: applying Kirchhoff's Voltage Law (KVL) around the loop givesI_sink = (V_DD - V_F - V_OL) / R = (3300 - 2050 - 150) mV / 1000 ohm = 1.10 mA(1100 uA), illuminating the LED well below a conservative8.0 mA(8000 uA) pad current limit!
Figure 1.3a. Physical CMOS pad stage — why active-low sink circuits conduct I = (V_DD - V_F - V_OL) / R when DR = 0 (left) vs active-high sourcing when DR = 1 (right).
Why do board designers prefer active-low sinking for status LEDs? Historically and physically, silicon NMOS electron mobility exceeds PMOS hole mobility (NMOS sinks low with lower on-resistance than PMOS sources high), and keeping indicator current off the 's high-side NVCC rail reduces supply bounce—provided the external series resistor R limits I_sink safely (R = 100 ohm would pull 11.0 mA, overstressing the pad!).
mental model: A schematic net label (LED0) is like a highway route number crossing county lines: the name can change at a border bridge (SOM-to-carrier connector), and the route name tells you connectivity—never which direction current flows or the pad's current limit.
Where it stops working: Unlike road traffic, electrical current requires a closed voltage loop (V_DD > V_F + V_OL), and shifting a signed 32-bit C integer into bit 31 invokes undefined behavior before a single electron moves.
definition (Schematic Net Continuity, Active-Low Sink & Peripheral Offset Geometry): A schematic net label joins electrically connected nodes on a drawing; tracing a signal from a carrier board load into a System-on-Module (SOM) requires following mating connector pin numbers (LED0 -> J1.14 -> P1.14 -> ball GPIO1_IO03), never guessing from text names. In an active-low sink circuit, logical assertion (on = true) drives the output bit to 0 (level_high = (on != active_low)). Each 32-bit register sits at physical address Base + Offset (GPIO1_DR = 0x0209C000 + 0x00, GPIO1_GDIR = 0x0209C000 + 0x04), where single-pin writes must preserve all 31 sibling bits.
Trace the complete four-stage path from external LED load to 32-bit register bitmask below:
- Step 1. Step 1 (Load Circuit): 3.3 V -> resistor -> LED -> GPIO cathode conducts when the pin sinks low (active-low).
- Step 2. Step 2 (Carrier Net): Follow net label LED0 to its exact board-to-board header pin and check shared pulls or boot straps.
- Step 3. Step 3 (Core Pad): Match the mating SOM connector pin to SoC ball GPIO1_IO03 (Bank 1, local bit index 3).
- Step 4. Step 4 (Register Mask): Compute Base + Offset (0x0209C000) and update bit 3 via UINT32_C(1) << pin without touching 31 siblings.
Figure 1.3b. Never guess polarity or GPIO numbers from net names: trace Load -> Connector Pin -> SoC Ball -> Masked Base+Offset.
Tracing Carrier Nets Across Connectors to Physical GPIO Registers
Most production i.MX6ULL hardware splits into two schematics: a compact Core SOM (housing the SoC, DDR3, PMIC, and eMMC/NAND) and a Carrier Board (housing LEDs, relays, UART headers, and Ethernet PHYs). Searching the SOM schematic PDF for LED0 often returns zero hits because the carrier net LED0 terminates on header J1 pin 14, while the mating SOM connector P1 pin 14 names that exact copper conductor GPIO1_IO03! Always build the four-column trace shown at the top of Figure 1.3b (Load Terminal -> Carrier Net/Pin -> SOM Pin/Ball -> Bank/Bit/Address) and note whether any external pull resistor shares a reset BOOT_CFG strap pin.
Figure 1.3b. Four-column schematic trace across board-to-board connectors (top) and 32-bit GPIO1 masked update geometry preserving all 31 sibling pins (bottom).
Once GPIO1_IO03 maps to Bank GPIO1 (0x0209C000), local bit 3, examine how schematic_gpio.c translates logical intent into an electrical level without scattering inverted 0/1 magic numbers across application code:
- Bounds-First Unsigned Shift (
pin < 32U+UINT32_C(1) << pin): InISO C11, shifting by>= 32on a32-bit type—or shifting signed literal1into sign bit31(1 << 31)—is Undefined Behavior (UB)! Checkingif (pin >= 32U) return false;before evaluatingUINT32_C(1) << pineliminates both traps. - Boolean XOR Polarity (
high = (on != active_low)): Whenactive_lowistrueand caller requestson = true,true != trueevaluates tofalse(0), clearing bit3(value & ~mask) to sink current while leaving all31siblingGPIO1pins untouched.
learner@ksa:~/gl-e01/m01-l03$ bat schematic_gpio.c File: schematic_gpio.c #include <stdint.h> #include <stdbool.h> static volatile uint32_t *const gpio1_dr = (volatile uint32_t *)(uintptr_t)0x0209c000U; bool led_write(unsigned pin, bool on, bool active_low) { if (pin >= 32U) return false; const uint32_t mask = UINT32_C(1) << pin; const bool high = on != active_low; uint32_t value = *gpio1_dr; /* exclusive bank ownership required */ value = high ? value | mask : value & ~mask; *gpio1_dr = value; return true; }Verifying KVL Sink Headroom, Polarity XOR, and Shift Safety in C11
Never dereference (volatile uint32_t *)0x0209c000U in a host process (where 0x0209C000 is an unmapped virtual address, not an i.MX6ULL IPG peripheral bus!). Instead, sink_drive_audit.c verifies both integer microampere KVL circuit analysis and 32-bit RAM-modeled GPIO1_DR bit preservation on the host. Notice how sink_current_ua() checks vdd_mv <= vf_mv + vol_mv before subtracting so an under-volted 1.8 V (1800 mV) rail driving a 2.05 V (2050 mV) red LED returns false cleanly instead of wrapping unsigned headroom to 4.29 GV, and rejects R = 100 ohm (11000 uA > 8000 uA).
learner@ksa:~/gl-e01/m01-l03$ bat -H 8 -H 9 -H 10 -H 11 -H 12 -H 13 -H 14 -H 15 -H 19 -H 20 -H 21 -H 22 -H 23 sink_drive_audit.c File: sink_drive_audit.c #include <assert.h> #include <stdbool.h> #include <stddef.h> #include <stdint.h> #include <stdio.h> static bool sink_current_ua(uint32_t vdd_mv, uint32_t vf_mv, uint32_t vol_mv, uint32_t r_ohm, uint32_t max_ua, uint32_t *out_ua) { if (r_ohm == 0U || vdd_mv <= vf_mv + vol_mv) return false; uint32_t headroom_mv = vdd_mv - vf_mv - vol_mv; uint32_t ua = (headroom_mv * 1000U) / r_ohm; if (ua == 0U || ua > max_ua) return false; *out_ua = ua; return true; } static bool set_pin_level(uint32_t *dr, unsigned pin, bool on, bool active_low) { if (dr == NULL || pin >= 32U) return false; uint32_t mask = UINT32_C(1) << pin; *dr = (on != active_low) ? (*dr | mask) : (*dr & ~mask); return true; } int main(void) { uint32_t ua = 0U; assert(sink_current_ua(3300U, 2050U, 150U, 1000U, 8000U, &ua) && ua == 1100U); assert(sink_current_ua(3300U, 2100U, 0U, 1200U, 8000U, &ua) && ua == 1000U); assert(!sink_current_ua(3300U, 2050U, 150U, 100U, 8000U, &ua)); assert(!sink_current_ua(1800U, 2050U, 150U, 1000U, 8000U, &ua)); assert(0x0209c000U + 0x04U == 0x0209c004U); uint32_t dr = 0xa5a5a5a5U, before = dr; assert(set_pin_level(&dr, 3U, true, true)); assert((dr & 8U) == 0U && (dr & ~8U) == (before & ~8U)); assert(set_pin_level(&dr, 3U, false, true) && (dr & 8U) != 0U); assert(set_pin_level(&dr, 3U, false, false) && (dr & 8U) == 0U); assert(set_pin_level(&dr, 3U, true, false) && (dr & 8U) != 0U); before = dr; assert(!set_pin_level(&dr, 32U, true, true) && dr == before); printf("sink_ua=1100 gdir=0x%08X dr_active_low_on=0x%08X\n", 0x0209c000U + 0x04U, before & ~8U); return 0; }- Evaluate (vdd_mv - vf_mv - vol_mv) * 1000 / r_ohm in uint32_t microamps and enforce the pad sink ceiling.
- Reject pin >= 32 before shifting UINT32_C(1) << pin so C11 shift-width undefined behavior never executes.
- Map logical assertion through (on != active_low) while preserving all 31 sibling bits in *dr.
Running the Circuit Current and Mask Verifier
Execute sink_drive_audit on the workstation and cross-compile schematic_gpio.c into freestanding ARMv7-A machine code (target.o) with -mfloat-abi=soft -ffreestanding -Werror to confirm clean target code generation alongside host algebraic verification.
learner@ksa:~/gl-e01/m01-l03gcc -std=c11 -Wall -Wextra -Werror -pedantic sink_drive_audit.c -o sink_drive_auditlearner@ksa:~/gl-e01/m01-l03./sink_drive_auditsink_ua=1100 gdir=0x0209C004 dr_active_low_on=0xA5A5A5A5learner@ksa:~/gl-e01/m01-l03clang --target=armv7a-none-eabi -mcpu=cortex-a7 -marm -mfloat-abi=soft -ffreestanding -std=c11 -Wall -Wextra -Werror -x c -c schematic_gpio.c -o target.olearner@ksa:~/gl-e01/m01-l03learner@ksa:~/gl-e01/m01-l03strace -e trace=write,exit_group \./sink_drive_auditwrite(1, "sink_ua=1100 gdir=0x0209C004 dr_"..., 57) = 57exit_group(0) = ?+++ exited with 0 +++End-to-End Signal Provenance and Drive Topology Trade-Offs
Compare the four drive and register patterns in the matrix below. Notice that led_write() updating GPIO1_DR at 0x0209C000 is necessary but still not sufficient to light the physical LED on cold silicon: Module 3 will add CCM_CCGR1 clock gating, IOMUXC ALT5 pad routing, SW_PAD_CTL DSE output drive, and GPIO1_GDIR (0x0209C004) output direction!
| Circuit / Software Choice | Drive Equation / Expression | Pin Stress & Sibling Safety | Failure Mode When Misapplied | |
|---|---|---|---|---|
direct GPIO sink (<= 2 mA) | dr &= ~(1U << pin) asserts; I = (V_DD - V_F - V_OL)/R | Safe within pad I_OL budget; 31 siblings preserved | Driving 1 turns LED off; omitting R overcurrents pad bond wire | |
Active-high direct GPIO source | `dr \ | = (1U << pin) asserts; I = (V_OH - V_F)/R` | Pulls current from NVCC rail; 31 siblings preserved | Fails to conduct if V_OH rail (1.8 V) sits below V_F (2.05 V) |
Whole-bank write *gpio1_dr = 0U | 1 store, 0 mask logic | Unsafe: clobbers all 31 neighboring GPIO1 pins | Asserts or drops unrelated relays, chip-selects, and reset lines on GPIO1 | |
Unchecked shift 1 << pin (signed int) | Undefined behavior for pin >= 31 in ISO C11 | Corrupts sign bit at pin == 31 or shifts out of bounds | Traps under -fsanitize=undefined or toggles wrong bit |
Later: Module 2 (m02-l01..m02-l03) dives inside the Cortex-A7 core itself—processor modes, banked registers, CP15 SCTLR/VBAR, load/store writeback, and 8-byte-aligned assembly stack frames—before Module 3 lights the physical LED in assembly and C.
Common Production Pitfalls
warning: Symptom: Searching the core SOM schematic for carrier net name LED0 yields zero matches, leading an engineer to guess GPIO1_IO00 and toggle an unrelated board net. Root Cause: Net names are local to a schematic sheet or hierarchy unless linked by ports; across a SOM-to-carrier header (J1 pin 14 -> P1 pin 14), the same electrical conductor is renamed GPIO1_IO03. Fix: Always trace signals by physical connector pin numbers from load terminal to SoC ball before writing software.
warning: Symptom: Calling set_pin_level(&dr, 31U, true, false) triggers a signed-overflow sanitizer abort when the mask is written 1 << pin instead of UINT32_C(1) << pin. Root Cause: Integer literal 1 has type signed int, and left-shifting 1 into sign bit 31 overflows INT32_MAX (Undefined Behavior in ISO C11). Fix: Reject pin >= 32U first and form every 32-bit register mask from unsigned UINT32_C(1) << pin.
Practice & Retrieval
Guided Practice: Sizing a 1.8 V Rail Indicator & Pin 31 Masking
Step 1 (1.8 V Headroom): A board revision moves an active-low indicator onto a 1800 mV (1.8 V) bank using a low-forward-voltage LED (V_F = 1200 mV, V_OL = 120 mV); solve (1800 - 1200 - 120) * 1000 / 1600 for series resistor R at 1600 uA (300 ohm). Step 2 (Pin 31 Polarity): Starting from dr = 0x80000008U, evaluate set_pin_level(&dr, 31U, true, true) in hex (0x00000008U). Step 3 (Offset Math): Given GPIO5 base 0x020AC000, state the physical addresses of GPIO5_DR (+0x00) and GPIO5_GDIR (+0x04).
Independent Practice: Worst-Case Tolerance & Netlist Auditor (board_led_spec.c)
Write a standalone ISO C11 verifier board_led_spec.c evaluating struct led_circuit across supply tolerance (vdd_min_mv, vdd_max_mv), LED drop spread (vf_min_mv, vf_max_mv), vol_max_mv, and resistor tolerance (r_nominal_ohm, r_tol_pct). Assert both worst-case visibility (I_min >= 500 uA at vdd_min, vf_max, R_max) and pad safety (I_max <= 6000 uA at vdd_max, vf_min, vol = 0, R_min) across 6 valid and faulted circuits.
→ open standalone lab workbench
1. Motivation
First-week Cortex-A7 bring-up sessions stall when an engineer downloads an x86_64 host binary (e_machine = 62) over TFTP into 0x87800000, trusts start + length <= base + size near 0xFFFFFFFF where 32-bit unsigned addition wraps modulo 2^32, or drives an active-low cathode-sink LED on GPIO1_IO03 with inverted Boolean logic that extinguishes the indicator when on == true. In this laboratory, you will audit starter/core.c, isolate a silent-compile polarity inversion inside pin_write(), and prove ELF32 EM_ARM identification, subtraction-based RAM placement bounds, and sibling-preserving GPIO data-latch updates under TAP version 13.
2. Learning Objectives
- Validate
32-bit little-endianARMELFheaders (0x7F 'E' 'L' 'F',EI_CLASS = 1,EI_DATA = 1,e_machine = 40at bytes18..19) while rejecting truncated buffers below20bytes. - Prove overflow-safe target RAM window containment
[start, start + length)inside[base, base + size)using post-guard subtraction (length <= size - (start - base)). - Repair active-low vs active-high
GPIOx_DRpin updates (on != active_low) sopin_write()preserves all31neighboring pins and rejectsNULLpointers orpin >= 32without mutating caller state. - Benchmark archive build and 4-suite verification latency (
p50/p95/p99) usingCLOCK_MONOTONIC.
3. Environment Requirements
- Tested Workstation Host:
Linux 7.0.0-42-generic(x86_64LP64user space) insidelabs/lab_m01_eabi_workbench/. - Target Architecture Alignment:
core.handcore.crestrict register images and RAM addresses to<stdint.h>uint32_tandUINT32_C(1)shifts so hostLP64verification matches32-bitARMv7-AILP32freestanding builds bit-for-bit.
4. Required Software & Hardware
- Software:
gcc(-std=c11 -Wall -Wextra -Werror -pedantic -MMD -MP), GNUmake, GNUar, POSIX/bin/sh, and Binutils (nm,readelf). - Hardware: Standard Linux workstation (
0physical target boards or serial adapters required for gradedTAPsign-off;3.3 Vactive-low sink verification applies during optional bench bring-up).
5. Complete Executable Commands
Run these commands from labs/lab_m01_eabi_workbench/ to reproduce the starter/ failure in a disposable sandbox, isolate failing test vectors 3 and 4, inspect the static archive libbsp.a, and confirm 5/5 TAP checks on files/:
learner@ksa:~/gl-e01/m01-l03$ bat script.sh File: script.sh # 1. Stage starter/ in a disposable temp directory and run check.sh without clobbering files/ TMP=$(mktemp -d) && cp -r check.sh tests.c starter "$TMP/" && mv "$TMP/starter" "$TMP/files" && sh "$TMP/check.sh" ; rm -rf "$TMP" # 2. Link tests.c directly against starter/core.c to pinpoint which case aborts TMP=$(mktemp -d) && gcc -std=c11 -Wall -Wextra -Werror -pedantic -Istarter tests.c starter/core.c -o "$TMP/v" && { "$TMP/v" 3 || echo "starter case 3 aborted (rc=$?)"; "$TMP/v" 4 || echo "starter case 4 aborted (rc=$?)"; } ; rm -rf "$TMP" # 3. Rebuild the reference library files/libbsp.a and inspect exported ABI symbols make -B -C files ar -t files/libbsp.a && nm -g --defined-only files/libbsp.a # 4. Run the authoritative 5-point TAP version 13 verification harness sh check.sh*Why each step runs:* Step 1 mirrors coursec labs by grading starter/ inside an isolated directory so files/ remains clean; Step 2 executes tests.c cases 3 and 4 directly to expose the SIGABRT exit codes (rc=134); Step 3 proves Makefile -MMD -MP compilation and archive symbol visibility (elf_arm32, image_fits, pin_write); and Step 4 emits graded TAP version 13 output.
6. Annotated Source Code (starter/core.c Defect vs files/core.c Fix)
elf_arm32(const unsigned char *p, size_t n)(core.c:2-7): Checksn >= 20Ubefore indexingp[0..5]andp[18..19], accepting only0x7f 'E' 'L' 'F',ELFCLASS32(1U),ELFDATA2LSB(1U), and little-endianEM_ARM(p[18] == 40U && p[19] == 0U).tests.ccase1rejectsn = 19U,ELFCLASS64(p[4] = 2U), andEM_X86_64(p[18] = 62U).image_fits(uint32_t base, uint32_t size, uint32_t start, uint32_t length)(core.c:8-13): Rejectsstart < baseorlength == 0Uup front, computesoffset = start - base, and checksoffset <= size && length <= size - offsetsostart = UINT32_MAX, length = 8Uintests.ccase2cannot wrap into range.- Seeded Flaw in
starter/core.c:18(pin_write):starterevaluates*dr = (on == active_low) ? *dr | mask : *dr & ~mask;(logical equivalence / XNOR). Whenon = trueandactive_low = true(cathode-sinkLEDon),starterdrives bit3high (3.3 V), turning theLEDoff; whenon = trueandactive_low = falseonpin = 31U(tests.c:34),starterclears bit31(0x12345678U) instead of setting0x92345678U. - Verified Repair in
files/core.c:14-20: Guardsif (dr == NULL || pin >= 32U) return false;beforeUINT32_C(1) << pin(avoiding C11 shift undefined behavior atpin == 32U), then writes*dr = (on != active_low) ? *dr | mask : *dr & ~mask;.
7. Expected TAP-13 Output
learner@ksa:~/gl-e01/m01-l03$ bat listing.txt File: listing.txt # Unmodified starter/ baseline (exits non-zero: # pass 3/5) TAP version 13 1..5 ok 1 - strict C11 build and trusted grader link ok 2 - recognizes ARM ELF32 and rejects short or mismatched headers ok 3 - accepts exact RAM fits and rejects arithmetic boundary violations not ok 4 - maps both output polarities and preserves sibling pins --- message: 'Behavior differs from the independently specified test vectors' hint: 'Repair case 3; inspect tests.c for the exact input and expected result' ... not ok 5 - rejects invalid pins without changing the output object --- message: 'Behavior differs from the independently specified test vectors' hint: 'Repair case 4; inspect tests.c for the exact input and expected result' ... # pass 3/5 # Repaired files/ implementation (sh check.sh -> exits 0: # pass 5/5) TAP version 13 1..5 ok 1 - strict C11 build and trusted grader link ok 2 - recognizes ARM ELF32 and rejects short or mismatched headers ok 3 - accepts exact RAM fits and rejects arithmetic boundary violations ok 4 - maps both output polarities and preserves sibling pins ok 5 - rejects invalid pins without changing the output object # pass 5/58. Explanation of Observed Behavior
In starter/, check 1 (ok 1), check 2 (ok 2), and check 3 (ok 3) pass cleanly because elf_arm32() and image_fits() are intact and (on == active_low) triggers zero -Wall -Wextra -Werror diagnostics. Check 4 (not ok 4) fails at tests.c:24: starting from dr = 0xa5a5a5a5U (where bit 3 is 0), pin_write(&dr, 3U, true, true) sets bit 3 (0xa5a5a5adU) instead of keeping before & ~8U. Check 5 (not ok 5) passes the pin = 32U and NULL guards at tests.c:32-33 but aborts at tests.c:34 because pin_write(&dr, 31U, true, false) clears bit 31 instead of producing 0x92345678U. Changing == to != in files/core.c satisfies all four polarity combinations (# pass 5/5).
9. Experiment Variations
- Signed-Shift Undefined Behavior at Pin 31 (
UBSan): ReplaceUINT32_C(1) << pinwith1 << pinin a scratch copy and compile with-fsanitize=undefined:tests.ccase4(pin = 31U) shifts1into the sign bit of32-bit signedint, triggering an immediate runtimeUBSandiagnostic. - Modular Addition Wrap in
image_fits(): Temporarily rewriteimage_fits()asreturn length > 0U && start >= base && start + length <= base + size;and runverify 2:UINT32_MAX + 8Uwraps to7U <= 0x1100U, falsely accepting a span past4 GiB. - Big-Endian
EM_ARMSpoof: Seth[18] = 0U; h[19] = 40U;(0x0028big-endian) in a scratch test and confirmelf_arm32()rejects mismatched byte order even whenEI_DATAclaims little-endian.
10. Performance Measurements
Timed on Linux 7.0.0-42-generic (x86_64) with CLOCK_MONOTONIC across 5 warmup runs and 35 measured iterations (reproduce binary timing via python3 -c 'import subprocess,time,statistics as s; [subprocess.run(["sh","check.sh"],stdout=-3) for _ in range(5)]; t=[(time.monotonic_ns(),subprocess.run(["sh","check.sh"],stdout=-3),time.monotonic_ns()) for _ in range(35)]; d=sorted((b-a)/1e6 for a,_,b in t); print(f"p50={s.median(d):.2f}ms p95={d[33]:.2f}ms")'):
Workload Measured (N = 35, warmup = 5) | Host p50 | Host p95 | Host p99 | Cortex-A7 @ 528 MHz Equivalent |
|---|---|---|---|---|
Full sh check.sh (make -B + gcc link + 4 processes) | 130.92 ms | 139.14 ms | 146.45 ms | Host-only toolchain step |
verify 4-case binary suite (verify 1..4 sequential) | 3434.1 us | 3861.1 us | 4202.8 us | < 2 us in-SRAM function calls (0 fork/exec) |
Single GPIO1_DR RMW (LDR + BIC/ORR + STR) | ~1 ns (L1 RAM) | ~2 ns | ~3 ns | ~40 - 90 ns across IPG peripheral bridge |
11. Troubleshooting
| Symptom | Root Cause | Fix | ||
|---|---|---|---|---|
not ok 4 & not ok 5 (# pass 3/5) | pin_write() uses (on == active_low) instead of (on != active_low) | Use `(on != active_low) ? *dr \ | mask : *dr & ~mask in core.c` | |
Shift warning or pin = 31 sign-extension corruption | 1 << pin shifts signed int instead of unsigned uint32_t | Form the bitmask as UINT32_C(1) << pin after checking pin < 32U | ||
verify 4 crashes with SIGSEGV | *dr read occurs before checking dr == NULL or pin >= 32U | Place `if (dr == NULL \ | \ | pin >= 32U) return false; on the first line of pin_write()` |
elf_arm32 accepts 256+ machine IDs | Checked p[18] == 40U without verifying high byte p[19] == 0U | Require both p[18] == 40U && p[19] == 0U for 16-bit little-endian e_machine |
12. Guided Questions
- Why must
pin_write()checkpin >= 32Ubefore evaluatingUINT32_C(1) << pin, even whenpin == 32Ureturnsfalseon the next line?
- *Hint 1:* Consult ISO C11 Section 6.5.7 on bitwise shift operators when the right operand equals or exceeds the promoted width of the left operand (
32bits). - *Hint 2:* On
x86_64,SHL eax, clmasksclmodulo32(1U << 32yields1!), whereas onARMv7-A,LSL Rd, Rm, Rsuses the bottom8bits ofRs(1U << 32yields0) -- the compiler may optimize assumingpin < 32Ualready holds!
- Why does an active-low cathode-sink
LEDrequireDR[pin] = 0foron == truewhile an active-high sourceLEDrequiresDR[pin] = 1?
- *Hint 1:* Trace the potential difference
V_DD - V_padacross the series resistor andLEDwhen the anode is tied to3.3 V. - *Hint 2:* Write the
2 x 2truth table of(on, active_low) -> pad_highand verify whypad_high = (on != active_low)covers all four rows.
13. Independent Challenges
- Near Transfer — Full
Elf32_Ehdr+PT_LOADSegment Gate: Extendelf_arm32()intoelf_arm32_loadable(const unsigned char *buf, size_t len, uint32_t ram_base, uint32_t ram_size)that parsese_phoff,e_phentsize == 32U, ande_phnum, rejectsp_memsz < p_filesz, and verifies everyPT_LOADsegment (p_type == 1U) fits[ram_base, ram_base + ram_size)viaimage_fits(). - Far Transfer — Multi-Pin Atomic Mask Update (
pin_group_write): Implementbool pin_group_write(uint32_t *dr, uint32_t group_mask, uint32_t logical_on, uint32_t active_low_mask)that updates an arbitrary subset of pins in one read-modify-write expression without per-pin loops while preserving all bits outsidegroup_mask.
14. Solutions & Explanations
- Guided Question 1: Shifting a
32-bituint32_tby>= 32is undefined behavior in ISO C11; evaluatingUINT32_C(1) << pinprior toif (pin >= 32U)lets an optimizing compiler elide thepin >= 32Ubranch altogether! - Guided Question 2: With anode at
3.3 V, drivingDR = 1(3.3 V) yields0 Vacross theLED(off), whereas drivingDR = 0(V_OL) forward-biases the diode (on). Across all four(on, active_low)pairs, the output latch bit is1when(true, false)or(false, true), which is exact Boolean inequalityon != active_low. - Challenge 2 Key Formula: Compute
desired_levels = logical_on ^ active_low_mask; *dr = (*dr & ~group_mask) | (desired_levels & group_mask);.
Run locally in your terminal and check off each verification milestone.
Not started
Key takeaways
- Schematic net labels denote electrical conductors on a sheet; always trace across mating SOM-to-carrier connector pin numbers to identify the exact
SoCball andGPIObank/bit. - sink circuits (
V_DD -> R -> LED -> GPIO) conductI = (V_DD - V_F - V_OL) / RwhenDRdrives0(level_high = (on != active_low)). - Peripheral registers sit at
Base + Offset(GPIO1_DR = 0x0209C000,GPIO1_GDIR = 0x0209C004); never dereference physicalSoCaddresses inside host user space. - Guard
pin < 32Ubefore evaluatingUINT32_C(1) << pinand use masked read-modify-write under exclusive ownership so all31sibling pins remain intact. - A schematic net label names electrical connectivity rather than a software GPIO number.
- An active-low LED connected from a supply through resistance to a GPIO conducts when the GPIO sinks current.
- No; it identifies a target address, not a host mapping.