velxio/test/test_circuit/plan/phase_5_avr_integration.md

66 lines
2.0 KiB
Markdown
Raw Normal View History

feat: electrical simulation via ngspice-WASM (eecircuit-engine) Adds full SPICE-accurate electrical simulation to Velxio, behind a lazy- loaded ⚡ toolbar toggle. Arduino / ESP32 / RP2040 sketches now co-simulate with real analog behaviour: correct voltages on wires, real I–V curves on LEDs, working potentiometers, NTC thermistors read by analogRead(), PWM driving RC filters, transistors, op-amps, diodes, MOSFETs, etc. Engine: eecircuit-engine (ngspice compiled to WebAssembly). Main bundle stays at 2.4 MB; the 20 MB SPICE chunk only loads when the user activates electrical mode. Disabled at build time via VITE_ELECTRICAL_SIM=false. Frontend additions: - simulation/spice/: SpiceEngine wrapper + lazy entry, NetlistBuilder with UnionFind over wires, componentToSpice mapping (24 metadataIds incl. real part numbers: 2N2222, 2N3055, BC547, IRF540, 2N7000, 1N4148, 1N4007, 1N4733, LEDs, NTC, op-amp ideal), CircuitScheduler with debounced coalescing, AVRSpiceBridge for quasi-static co-simulation. - store/useElectricalStore: Zustand slice, feature-flag aware. - components/analog-ui/: ⚡ toolbar toggle + SVG voltage overlay. - components/components-instruments/: Voltmeter, Ammeter probes. - 62 tests (spice-*, netlist-builder, component-to-spice, instruments). Sandbox (test/test_circuit/): 47-test validation sandbox that proved the approach (hand-rolled MNA baseline + ngspice pipeline) before porting to the app. Kept as reference. Docs: docs/wiki/circuit-emulation-*.md (13 engineering pages covering architecture, solvers, components, AVR bridge, gotchas, performance, integration plan, API reference, appendix) + electrical-simulation- user-guide.md (end-user facing). Reference plan: test/test_circuit/plan/phase_8_velxio_implementation.md Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-15 19:11:54 +07:00
# Fase 5 — Integración con avr8js
## Cómo Velxio usa avr8js
`frontend/src/simulation/AVRSimulator.ts`:
```typescript
this.cpu = new CPU(programUint16, sramBytes);
this.portB = new AVRIOPort(this.cpu, portBConfig);
this.adc = new AVRADC(this.cpu, adcConfig);
this.peripherals = [new AVRTimer(this.cpu, timer0Config), ...];
// En el loop:
avrInstruction(this.cpu);
this.cpu.tick();
// Inyectar voltaje analógico:
this.adc.channelValues[channel] = voltage; // 05V
```
Velxio dispara listeners de pines al escribir PORTB/C/D y enruta al PinManager. Los ADC se leen cuando el sketch hace `analogRead`.
## En la sandbox replicamos ese patrón
`src/avr/AVRHarness.js`:
- Carga .hex via `hexToUint8Array` (implementado localmente, mismo formato Intel HEX)
- Instancia `CPU`, `AVRIOPort`, `AVRADC`, `AVRTimer` igual que Velxio
- Expone `step(cycles)`, `setAnalogVoltage(channel, v)`, `getPin(arduinoPin)`, `onPinChange(pin, cb)`, `getPWMDuty(pin)`
## Puente circuito ↔ MCU
`src/bridge/CircuitAVRBridge.js`:
```
cada N ciclos (por defecto cada 1 ms):
1. leer estado GPIO → actualiza VoltageSources del circuito
2. leer duty PWM → actualiza V_pwm = Vcc · duty
3. solveDC() del circuito
4. inyectar voltajes de nodos conectados a pines ADC
```
## HEX files requeridos
Como no tenemos `avr-gcc` disponible, usamos:
- HEX **ensamblada a mano** para blink y programas simples
- HEX de `frontend/src/__tests__/fixtures/avr-blink/avr-blink.ino.hex` (copiada)
- Para el test de potenciómetro + PWM escribimos un loop AVR assembly mínimo que:
1. Inicia ADC (ADMUX=0x40 para AVCC ref + canal 0; ADCSRA=0x87)
2. Dispara conversión (set ADSC)
3. Espera fin
4. Escribe ADCH en OCR1AL (PWM timer1)
5. Salta al paso 2
Ese programa cabe en ~30 instrucciones y se asembla manualmente a bytes.
## Archivos
- `src/avr/AVRHarness.js`
- `src/avr/intelHex.js`
- `src/bridge/CircuitAVRBridge.js`
- `test/avr_blink.test.js`
- `fixtures/blink.hex` — del fixture existente de Velxio
- `fixtures/pot_pwm.hex` — ensamblada a mano