# Digital Circuit Simulation Guide This guide explains how wiRedPanda brings your digital circuits to life through simulation, covering both user-friendly explanations and technical implementation details. ## Quick Reference **wiRedPanda's Simulation at a Glance:** - 🎯 **Model:** Hybrid (immediate propagation + tick-based) - ⏱️ **Update Rate:** 1ms intervals - 🔄 **Feedback Handling:** Selective iterative convergence (max 10 iterations) - 📊 **Logic States:** Three-state (Invalid, Inactive, Active) - 🏭 **Best For:** Educational use, learning digital logic ## Why This Matters to You Understanding simulation helps you: - **📚 Learn better**: Know why circuits behave the way they do - **🔧 Build better circuits**: Understand timing and feedback behavior - **🤝 Contribute effectively**: Grasp the technical foundation for contributions - **🎓 Teach confidently**: Explain simulation concepts to students Whether you're a curious user or potential contributor, this guide bridges the gap between "what you see" and "how it works." ## Overview Digital circuit simulation involves modeling the behavior of logic circuits over time. Different simulation models offer trade-offs between accuracy, performance, and implementation complexity. Understanding these models is crucial for both users and developers of circuit simulators. ## wiRedPanda's Simulation Model **wiRedPanda uses a hybrid approach** combining elements of immediate propagation and tick-based simulation: ```mermaid graph TB subgraph "Hybrid Simulation Model" A[Circuit Input] --> B{Has Feedback?} B -->|No| C[Single-Pass Logic Update] B -->|Yes| D[Iterative Convergence] C --> E[Connection Updates] D --> E E --> F[Output Elements] F --> G[1ms Timer Tick] G --> A end style A fill:#e1f5fe style F fill:#e8f5e8 style D fill:#fff3e0 ``` ### Current Implementation - **Primary Model**: **Immediate Propagation** for combinational logic - Changes propagate instantly through most combinational circuits - **Selective iterative convergence** applied only to elements in feedback loops - Non-feedback circuits maintain fast single-pass evaluation - Timer-based updates at 1ms intervals for real-time simulation - **Sequential Elements**: **Tick-based updates** for memory components - Flip-flops, latches, and counters update on clock edges - Memory elements maintain state between ticks - Proper handling of setup/hold timing relationships - **Logic States**: **Three-state logic** with precise semantics ```mermaid stateDiagram-v2 [*] --> Invalid [*] --> Inactive [*] --> Active Invalid : -1 (Unconnected/Error) Inactive : 0 (Logic Low) Active : 1 (Logic High) Invalid --> Inactive : Connection established Invalid --> Active : Connection established Inactive --> Active : Signal change Active --> Inactive : Signal change Inactive --> Invalid : Connection lost Active --> Invalid : Connection lost ``` - **Invalid (-1)**: Unconnected inputs, error conditions - **Inactive (0)**: Logic low, false - **Active (1)**: Logic high, true ### Cross-Coupling and Feedback Handling wiRedPanda includes **sophisticated feedback loop handling** with selective iterative convergence: #### Feedback Loop Detection Algorithm ```mermaid flowchart TD A[Start Circuit Analysis] --> B[Initialize DFS Stack] B --> C[Select Next Element] C --> D{Element in Stack?} D -->|Yes| E[Mark as Feedback Loop] D -->|No| F[Add to Stack] F --> G[Process Dependencies] G --> H{More Dependencies?} H -->|Yes| C H -->|No| I[Remove from Stack] I --> J{More Elements?} J -->|Yes| C J -->|No| K[Analysis Complete] E --> L[Flag inFeedbackLoop] L --> K style E fill:#ffebee style L fill:#ffebee style K fill:#e8f5e8 ``` - **Depth-first search** with cycle detection during circuit initialization - **Stack-based detection**: Elements already in processing stack indicate feedback loops - **Automatic flagging**: Elements in cycles are marked with `inFeedbackLoop()` flag - **Priority-aware**: Feedback elements get special priority handling to break circular dependencies #### Iterative Convergence Process ```mermaid flowchart TD A[Feedback Elements Detected] --> B[Initialize: iteration = 0] B --> C[Store Previous Outputs] C --> D[Update All Logic Elements] D --> E[Compare with Previous] E --> F{Values Changed?} F -->|No| G[Converged - Success] F -->|Yes| H{iteration < 10?} H -->|Yes| I[iteration++] I --> C H -->|No| J[Max Iterations - Warning] J --> G style G fill:#e8f5e8 style J fill:#fff3e0 style A fill:#e1f5fe ``` - **Selective activation**: Only runs when `hasFeedbackElements` is detected in circuit - **Maximum 10 iterations** to prevent infinite loops in unstable circuits - **Convergence detection**: Compares output values between iterations to detect stability - **Early termination**: Stops immediately when all outputs stabilize (most cases converge in 2-3 iterations) - **Performance preservation**: Non-feedback elements maintain single-pass speed #### Supported Feedback Scenarios - **Cross-coupled gates**: NAND/NOR latches built from basic gates - **Combinational feedback loops**: Any circular dependency in logic elements - **Mixed circuits**: Feedback elements coexist with fast single-pass combinational logic - **Warning system**: Logs warnings for circuits that fail to converge after 10 iterations ### Why This Approach? **Educational Focus**: The hybrid model balances accuracy with simplicity, making it ideal for learning: - **Immediate feedback** for combinational circuits helps students understand logic flow - **Proper clocking** for sequential elements teaches timing concepts - **Simplified state model** reduces complexity for beginners **Performance**: Optimized simulation engine suitable for interactive learning: - **Real-time updates** at 1ms intervals for responsive visualization - **Selective processing**: Only feedback elements use iterative solving - **Fast convergence**: Most feedback circuits stabilize in 2-3 iterations - **Efficient scaling**: Performance impact limited to actual feedback complexity ### Limitations and Considerations **What wiRedPanda handles well:** - Basic combinational and sequential logic - **Cross-coupled circuits** and feedback loops (with iterative convergence) - **Complex latches** built from basic gates - Clock-driven circuits with clear timing - Educational circuit examples and projects **What to be aware of:** - **Propagation delays** are abstracted away for simplicity - **Metastability** and other advanced timing effects are not simulated - **Oscillating circuits** may be detected but behavior depends on convergence algorithm - **Large circuits with extensive feedback** may experience performance limitations due to iterative solving ### Future Considerations The simulation model continues to evolve based on educational needs and user feedback. Potential enhancements might include: - More sophisticated timing models for advanced users - Enhanced state visualization for debugging complex feedback circuits - Improved performance optimizations for very large circuits ## Technical Implementation Details ### Circuit Analysis Phase During initialization, wiRedPanda performs comprehensive circuit analysis: 1. **Element Collection**: Gathers all logic elements, connections, and I/O components 2. **Priority Calculation**: Uses depth-first search to assign processing priorities 3. **Feedback Detection**: Identifies circular dependencies using stack-based cycle detection 4. **Mapping Creation**: Builds optimized data structures for simulation execution ### Simulation Loop Structure ```mermaid flowchart TD A[1ms Timer Tick] --> B[Update Clocks] B --> C[Update Input Elements] C --> D{Feedback Elements?} D -->|Yes| E[Iterative Convergence
max 10 iterations] D -->|No| F[Single-Pass Logic Update
priority order] E --> G[Update Connection Ports] F --> G G --> H[Refresh Output Elements] H --> I[Wait for Next Tick] I --> A style A fill:#e1f5fe style E fill:#fff3e0 style F fill:#e8f5e8 style H fill:#e8f5e8 ``` ### State Validation System - **Connection validation**: Ensures all inputs are properly connected - **Logic validation**: Propagates validity through element chains - **Error handling**: Invalid elements marked and excluded from simulation - **Port status updates**: Visual feedback reflects logical state changes ## Reference: General Digital Circuit Simulation Models > 📚 **Educational Reference Section** > *The following sections provide background on different simulation approaches used in digital circuit simulators. This information helps understand the broader context of simulation techniques, though wiRedPanda's specific implementation is described above.* ## 1. Immediate Propagation (Direct Evaluation) ```mermaid graph LR A[Input Change] --> B[Component 1] B --> C[Component 2] C --> D[Component 3] D --> E[Output] style A fill:#e1f5fe style E fill:#e8f5e8 style B fill:#fff3e0 style C fill:#fff3e0 style D fill:#fff3e0 ``` **How it works:** - Components are processed sequentially, one at a time - Each component updates its outputs immediately before moving to the next - Changes propagate through the circuit instantly **Advantages:** - Simple to implement and understand - Fast execution for basic circuits - Minimal memory requirements **Limitations:** - Results depend on the order components are processed - Cannot accurately model real hardware timing - May miss race conditions and glitches - Not suitable for complex sequential circuits **Use cases:** Basic educational simulators, simple combinational logic ## 2. Tick-Based (Synchronous) Simulation ```mermaid timeline title Tick-Based Simulation Timeline Tick 0 : All components read inputs : Calculate new states : Wait for tick end Tick 1 : Apply all updates simultaneously : New clock edge : Sequential elements update Tick 2 : Repeat process : Synchronous operation : Predictable timing ``` **How it works:** - Circuit evaluation occurs in discrete time steps called "ticks" - All components calculate their new states simultaneously - Updates are applied at the end of each tick - Clock edges and timing are explicitly modeled **Advantages:** - Order-independent evaluation - Accurately models clocked digital systems - Handles sequential circuits correctly - Predictable timing behavior **Limitations:** - May not reflect pure combinational logic behavior - Requires careful handling of asynchronous elements - Clock model must be well-defined **Use cases:** Synchronous digital circuits, CPU simulation, FPGA design ## 3. Event-Driven Simulation ```mermaid graph TD A[Input Change Event] --> B[Event Queue] B --> C[Process Next Event] C --> D[Update Component] D --> E{Generate New Events?} E -->|Yes| F[Schedule Future Events] E -->|No| G{Queue Empty?} F --> B G -->|No| C G -->|Yes| H[Simulation Complete] style A fill:#e1f5fe style B fill:#fff3e0 style H fill:#e8f5e8 ``` **How it works:** - Only components that receive input changes are updated - Events are scheduled in a priority queue with timestamps - Components process events and may generate future events - Propagation delays can be accurately modeled **Advantages:** - Highly efficient for sparse activity - Accurate delay modeling - Scales well to large circuits - Industry-standard approach **Limitations:** - Complex implementation - Requires sophisticated event scheduling - Memory overhead for event queues **Use cases:** Professional simulators (Verilog, VHDL), large-scale circuit analysis ## 4. Levelized (Topological) Simulation ```mermaid graph TB subgraph "Level 0" A[Input 1] B[Input 2] end subgraph "Level 1" C[Gate 1] D[Gate 2] end subgraph "Level 2" E[Gate 3] end subgraph "Level 3" F[Output] end A --> C B --> C A --> D B --> D C --> E D --> E E --> F style A fill:#e1f5fe style B fill:#e1f5fe style F fill:#e8f5e8 ``` **How it works:** - Circuit topology is analyzed to determine evaluation order - Components are processed in levels that guarantee correct propagation - No feedback loops within a single level **Advantages:** - Deterministic evaluation order - More accurate than immediate propagation - Suitable for synthesis and analysis tools **Limitations:** - Requires preprocessing for level assignment - Cannot handle circuits with feedback loops directly - May need iterative solutions for complex dependencies **Use cases:** Logic synthesis, static timing analysis, gate-level simulation ## Clock Models and Timing ### Tick Definitions The meaning of a "tick" varies between simulation models: **Half-Tick Model:** - One tick = one clock edge (rising OR falling) - Full clock cycle = two ticks - Better for edge-triggered components - More precise timing control **Full-Tick Model:** - One tick = complete clock cycle (rising AND falling) - Simpler for level-based logic - Less timing precision ### Clock Edge Detection Proper clock edge detection is critical for sequential elements: ```mermaid stateDiagram-v2 [*] --> Low Low --> Rising : Clock 0→1 Rising --> High : Edge detected High --> Falling : Clock 1→0 Falling --> Low : Edge detected Low : Previous=0, Current=0 High : Previous=1, Current=1 Rising : Previous=0, Current=1 (Edge!) Falling : Previous=1, Current=0 (Edge!) ``` ## Logic States and Values ### Basic Two-State Logic (0, 1) Sufficient for simple combinational circuits where all inputs are well-defined. ### Multi-State Logic (0, 1, X, Z) **Recommended for realistic simulation:** - **0**: Logic low - **1**: Logic high - **X**: Unknown/undefined/indeterminate - **Z**: High impedance (tri-state) ### Benefits of Multi-State Logic 1. **Uninitialized State Detection** - Flip-flops and latches start in unknown state (X) - Prevents masking of initialization bugs - More accurately reflects real hardware 2. **Error Propagation** - Unknown inputs produce unknown outputs - Helps identify timing and initialization issues - Makes debugging more effective 3. **Tri-State Support** - Essential for bus systems - Models multiple drivers correctly - Prevents bus conflicts 4. **Invalid State Handling** - SR latch with S=1, R=1 → outputs X - Makes design errors visible ### Truth Tables with X States #### AND Gate Truth Table | A | B | Output | |---|---|--------| | 0 | 0 | 0 | | 0 | 1 | 0 | | 0 | X | 0 | | 1 | 0 | 0 | | 1 | 1 | 1 | | 1 | X | X | | X | 0 | 0 | | X | 1 | X | | X | X | X | ## Memory and Sequential Elements ### Common Simulation Issues 1. **Tick Ordering Problems** - Memory updates in the same tick it's written - **Solution**: Use previous tick's value for reads 2. **Clock Edge Mishandling** - Updates on any clock change instead of specific edges - **Solution**: Explicit edge detection with state tracking 3. **Uninitialized Memory** - Memory defaults to 0 instead of unknown state - **Solution**: Initialize memory cells to X state 4. **Feedback Loop Timing** - Simultaneous read/write in latches causes instability - **Solution**: Separate input sampling from output updates ### Sequential Element Guidelines #### D Flip-Flop Behavior | Clock Edge | D Input | Q Output (next tick) | |------------|---------|---------------------| | Rising | 0 | 0 | | Rising | 1 | 1 | | No Edge | X | Q (unchanged) | #### SR Latch Truth Table | S | R | Q(next) | |---|---|-------------| | 0 | 0 | Q (hold) | | 0 | 1 | 0 (reset) | | 1 | 0 | 1 (set) | | 1 | 1 | X (invalid) | ## Testing and Validation ### Essential Test Cases #### 1. Basic Functionality Tests **Write-Read Delay Test:** ```text Tick 1: Write value 0x42 to memory address 0 Tick 2: Read from address 0 Expected: Should return 0x42 ``` **Clock Edge Detection:** ```text D = 1, Clock = 0 → Q unchanged Clock transition 0→1 → Q becomes 1 Clock = 1 (no transition) → Q remains 1 ``` #### 2. Timing and Race Condition Tests **Propagation Delay:** ```text Input A changes from 0→1 All downstream gates should update in correct order No intermediate glitches should affect final result ``` **Hazard Detection:** ```text Circuit: (A AND B) OR (A AND C) A=1, B=0, C transitions 0→1 Output should remain stable (no glitch) ``` #### 3. State and Memory Tests **Latch Hold Behavior:** ```text SR Latch: S=1, R=0 → Q=1 Then: S=0, R=0 → Q should remain 1 ``` **Uninitialized Memory:** ```text Read from fresh memory location Should return X (unknown), not 0 or 1 ``` #### 4. Error Detection Tests **Invalid States:** ```text SR Latch with S=1, R=1 Should produce X output, not arbitrary 0 or 1 ``` **Floating Inputs:** ```text Gate with disconnected input Should handle gracefully (default to 0, 1, or X) ``` ## Performance Considerations ### Optimization Strategies #### 1. Lazy Evaluation - Only update components when inputs change - Skip processing of inactive circuit regions #### 2. Level Compilation - Pre-compute evaluation order - Minimize dependency checking during simulation #### 3. Event Filtering - Suppress redundant events (value didn't actually change) - Reduce unnecessary propagation #### 4. Parallel Processing - Evaluate independent circuit regions in parallel - Use multiple threads for large circuits ### Memory Management - **Sparse Representation**: Only store non-default states - **Event Pooling**: Reuse event objects to reduce allocation - **Incremental Updates**: Only recompute changed portions ## Implementation Guidelines ### For Simulator Developers 1. **Choose the Right Model** - Educational tools → Tick-based with multi-state logic - High-performance → Event-driven - Synthesis tools → Levelized simulation 2. **State Management** - Always support X (unknown) state - Consider Z (tri-state) for bus systems - Initialize sequential elements to X 3. **Clock Handling** - Implement proper edge detection - Support both positive and negative edge triggering - Handle clock domain crossing carefully 4. **Testing Strategy** - Create comprehensive test suites - Include edge cases and error conditions - Validate against known good results ### For Circuit Designers 1. **Initialization** - Always initialize flip-flops and counters - Don't rely on power-on state assumptions - Use reset signals for deterministic startup 2. **Timing** - Understand your simulator's timing model - Avoid combinational loops without proper clocking - Consider setup and hold time requirements 3. **Debugging** - Use X states to identify initialization issues - Check for unintended latches in combinational logic - Verify clock domain crossing designs ## Advanced Topics ### Metastability Real flip-flops can enter metastable states when setup/hold times are violated. Advanced simulators may model this as: - Temporarily outputting X - Random resolution to 0 or 1 after delay - Probability-based resolution ### Power and Thermal Effects Some simulators include: - Power consumption estimation - Temperature effects on timing - Voltage level variations ### Mixed-Signal Simulation Integration with analog simulators for: - ADC/DAC interfaces - Power supply modeling - Signal integrity analysis > 💡 **Key Takeaway** > This guide provides the foundation for understanding digital circuit simulation. The choice of simulation model depends on your specific requirements for accuracy, performance, and implementation complexity. ## Next Steps Now that you understand how wiRedPanda's simulation works: ### 🎓 **For Users & Educators** - 🏠 **Apply this knowledge** → [Home](Home.md) (use wiRedPanda more effectively) - 🎯 **Build complex circuits** with confidence in timing and feedback behavior - 📚 **Teach simulation concepts** using wiRedPanda as a demonstration tool ### 🛠️ **For Contributors** - 🔧 **Create custom elements** → [Element Creation Guide](How-to-create-a-new-logic-element.md) - 👨‍💻 **Contribute to codebase** → [Development Setup](How-to-setup-environment.md) - 📚 **Use Git effectively** → [Git Guide](Git-Guide.md) ### 🌍 **For Community Members** - 💬 **Share insights**: [GitHub Discussions](https://github.com/GIBIS-UNIFESP/wiRedPanda/discussions) - 🌐 **Help translate** → [Translation Guide](How-to-translate.md) - ⭐ **Support the project**: [GitHub Repository](https://github.com/GIBIS-UNIFESP/wiRedPanda) ### 🔬 **For Advanced Users** - 🎛️ **Experiment** with feedback loops and complex timing - 📊 **Analyze** circuit performance characteristics - 🏗️ **Design** educational examples showcasing simulation concepts **Understanding simulation makes you a more effective wiRedPanda user and contributor!** 🚀 --- *Made with ❤️ by the wiRedPanda Community* *Licensed under GPL-3.0 | © 2025 GIBIS-UNIFESP*