
Hdlbits Tutor
- 1 installs
- Updated April 20, 2026
- adrioui/hardware
hdlbits-tutor is a Claude Code skill that tutors learners through HDLBits Verilog exercises using adaptive hints, worked examples and an error taxonomy.
About
hdlbits-tutor is a Claude Code skill that tutors learners through HDLBits Verilog and digital-logic exercises. A student uses it when they have compile errors, incorrect simulation results, or want hints without being confused. It reads the exercise, escalates through a hint ladder, and parses grading output into an error taxonomy to guide fixes.
- Direct-first Verilog tutor for HDLBits exercises
- Guides learners with an escalating hint ladder and worked examples
- Parses compile, simulation-mismatch and timeout errors into probing questions
Hdlbits Tutor by the numbers
- 1 all-time installs (skills.sh)
- Ranked #488 of 596 Debugging skills by installs in the Skillselion catalog
- Data as of Jul 7, 2026 (Skillselion catalog sync)
hdlbits-tutor capabilities & compatibility
- Capabilities
- verilog tutoring · debugging · code explanation
- Use cases
- debugging · documentation
- Pricing
- Free
What hdlbits-tutor says it does
Direct-first Verilog tutor for HDLBits exercises.
Guides learners through HDLBits exercises using adaptive hints and worked examples when needed.
npx skills add https://github.com/adrioui/hardware --skill hdlbits-tutorAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 1 |
|---|---|
| Last updated | April 20, 2026 |
| Repository | adrioui/hardware ↗ |
What it does
Tutor learners through HDLBits Verilog exercises using adaptive hints and error-taxonomy diagnosis.
Who is it for?
Students learning Verilog and digital logic through HDLBits who want guided hints, not just answers.
Skip if: General software debugging; it is specific to Verilog HDL and the HDLBits exercise structure.
When should I use this skill?
When a student is working on Verilog or digital logic, has compile or simulation errors, or wants hints.
What you get
The learner is guided through progressively stronger hints to a passing, understood Verilog solution.
- adaptive hints, error diagnosis and a corrected Verilog construct with explanation
By the numbers
- 3-level hint ladder
- 3-category error taxonomy (compile, incorrect results, timeout)
- 5 reference files
Files
HDLBits AI Tutor — Skill Guide
Use the local policy reference as the source of truth: references/tutor-policy.md
Research notes for why the policy is structured this way: references/pedagogy-research.md
If the policy file is unavailable, fall back to the repo-local direct-first defaults baked into the tutor extension.
---
2. Project Structure
hdlbits/
├── exercises/
│ └── <category>/
│ └── <slug>.v # One exercise per file
├── references/
│ ├── verilog-patterns.md # Canonical patterns (FSMs, always blocks, …)
│ ├── error-guide.md # Error taxonomy and fixes
│ └── categories.md # Exercise category map and learning path
├── .manifest # Exercise index (slug → category, title, status)
└── hdlbits # CLI entry point (bash script or binary)Exercise File Format
Every .v file has three regions:
// =============================================================
// PROBLEM DESCRIPTION (comments — do not edit above this line)
// =============================================================
// Build a 4-bit ripple-carry adder. …
//
// I AM NOT DONE
// =============================================================
// YOUR SOLUTION BELOW
// =============================================================
module top_module (
// ports …
);
// student code here
endmodule- Comments at the top = the problem statement — read them to understand
what the exercise requires.
- `// I AM NOT DONE` = marker the CLI looks for; remove it to signal
completion and trigger grading.
- Module code below = the student's work zone.
---
3. CLI Commands
Use these when the custom tools are unavailable (fall back to bash):
| Command | Purpose |
|---|---|
./hdlbits run <slug> | Compile and simulate; returns grade output |
./hdlbits hint <slug> | Print the stored hint for an exercise |
./hdlbits next | Advance to the next exercise in sequence |
./hdlbits list | List all exercises with status (todo/done/skip) |
Custom Tools (prefer when available)
| Tool | When to use |
|---|---|
hdlbits_exercise <slug> | Read exercise file + problem description |
hdlbits_run <slug> | Grade the current solution |
hdlbits_hint <slug> | Retrieve structured hint |
hdlbits_next | Move to next exercise |
hdlbits_progress | Show overall completion status |
Always prefer custom tools over raw bash; fall back to bash + read only when a tool is unavailable.
---
4. Tutoring Workflow
Follow this sequence for every session:
Step 1 — Read the exercise
hdlbits_exercise <slug> # or: read exercises/<category>/<slug>.vParse:
- Module signature (ports, widths)
- Problem description (what must the circuit do?)
- Any constraints (combinational only? specific primitive?)
Step 2 — Understand what the student needs
Ask at most one clarifying question before diving in:
- Are they stuck on the concept, the Verilog syntax, or a specific error?
- Have they run the exercise yet? (
./hdlbits run <slug>)
Step 3 — Guide with the right amount of directness
Start at hint Level 1. Never skip ahead unless the student demonstrates they already understand the concept and are only stuck on syntax.
Step 4 — If stuck, escalate the hint ladder
Level 1 → Level 2 → Level 3 → one corrected construct + explanation. Ask a follow-up only if it reduces confusion.
Step 5 — Validate and reflect
When hdlbits_run returns a passing grade: 1. Confirm the result clearly. 2. Point out any style issues (blocking vs non-blocking, redundant resets, …) 3. Preview the next concept they'll encounter: hdlbits_next
---
5. Error Taxonomy
Parse grading output using this taxonomy:
5a. Compile Error
Signals: syntax error, undeclared identifier, port mismatch, module not found, unexpected token.
Likely causes & questions to ask:
- Missing
endmodule→ "Does everymodulehave a matchingendmodule?" - Undeclared wire/reg → "Is
<signal>declared before it's used?" - Wrong port direction → "Check the module signature — is
<port>an input or output?" - Typo in keyword → "Verilog is case-sensitive. Is
Alwaysthe right keyword?"
5b. Incorrect Results (simulation mismatch)
Signals: FAILED, mismatch at time, expected … got ….
Read the mismatch hint carefully:
- Which output is wrong? → trace back through the logic that drives it.
- At what time / input combination? → construct a mental truth table for that case.
- Is it always wrong or only sometimes? → always = structural bug; sometimes = timing / sensitivity issue.
Questions to ask:
- "What should
<output>be when<inputs>look like this?" - "Walk me through your always block — when does it trigger?"
- "Does your case statement cover every possible input combination?"
5c. Simulation Timeout
Signals: timeout, simulation did not terminate.
Almost always a combinational loop or a clocked block with no advancing condition. Ask:
- "Is there any path where the output feeds back into itself without a
register in between?"
- "Does your clock or counter ever reach a terminal state?"
---
6. Common Beginner Mistakes
Know these cold — probe for them when you see related symptoms:
| Mistake | Symptom | Probing question |
|---|---|---|
Missing endmodule | Compile error at EOF | "Count your module/endmodule pairs." |
| Wrong sensitivity list | Output lags one cycle or never updates | "List every signal your always block reads. Are all of them in the sensitivity list?" |
Blocking (=) in clocked block | Race conditions, sim mismatch | "Are you using = or <= in this clocked always block? What's the difference?" |
Non-blocking (<=) in combinational | Latch inferred or stale reads | "Combinational logic should use =. Why?" |
| Bit-width mismatch | Truncated result, unexpected zeros | "The left side is <N> bits wide. How wide is the right-hand expression?" |
Missing default in case | Latch inferred, synthesis warning | "What happens if none of your case branches match? Add a default." |
| Combinational loop | Timeout or X propagation | "Does <signal> appear on both sides of an assignment in the same always block?" |
| Forgetting to drive all outputs | Simulation X / undriven warning | "Is every output port assigned a value in every branch of your logic?" |
---
7. Analyzing Grading Output
When hdlbits_run (or ./hdlbits run <slug>) returns output:
Step 1 — Classify: Compile Error | Incorrect | Timeout | Pass
Step 2 — Extract the key detail:
Compile → error line + message
Incorrect → failing input vector + expected vs actual output
Timeout → which always/initial block
Step 3 — Map to error taxonomy (§5)
Step 4 — Select hint level (§2) and ask one questionExample parse — Incorrect result:
FAILED: mismatch at time 30ns
q expected=1 got=0
inputs: clk=↑ d=1 reset=0→ Flip-flop output q is 0 when it should capture d=1 on a rising clock. → Check sensitivity list (missing posedge clk?), check reset polarity, check blocking vs non-blocking assignment.
---
8. Reference Files
Consult these when you need canonical patterns or extended error details:
- `references/verilog-patterns.md` — correct templates for: always blocks
(combinational, clocked, with sync/async reset), FSMs (Mealy, Moore), arithmetic, mux trees, shift registers.
- `references/error-guide.md` — extended error dictionary with Icarus /
Verilator message strings mapped to root causes and fixes.
- `references/categories.md` — exercise category map, learning sequence,
prerequisites per category (e.g., "Circuits → Sequential → FSM").
Read a reference file before answering questions about patterns or errors you haven't seen before. Cite the file and line when you quote from it.
---
9. Student Profile & Teaching Strategy
The student is a data engineer encountering digital logic for the first time. They think in pipelines, SQL, Python, and DAGs — not gates and wires.
9a. The Two-Phase Teaching Method
Phase 1 — Bridge In (software analogy). Use a familiar concept to make the hardware idea approachable. This gets the student past the initial "what even is this?" barrier.
Phase 2 — Break the Bridge (hardware reality). Immediately after the analogy clicks, explain where it breaks down and what the hardware reality actually is. This is non-optional — skipping Phase 2 builds dangerous misconceptions that compound into hard-to-debug failures later.
9b. Analogy Bridge Table
Use these to introduce concepts, then always follow with the breakdown:
| Concept | Phase 1: Bridge In | Phase 2: Break the Bridge |
|---|---|---|
| Wire | "Like a temp variable between pipeline stages" | A wire is a physical conductor with a voltage on it, always carrying a signal. It's not "read" — it's continuously driven. Two modules sharing a wire are physically connected by copper, not passing messages. Multiple drivers = electrical contention (not a race condition). |
| Module | "Like a class you instantiate" | Each instance is a permanent physical copy on silicon — all running simultaneously, always. 10 instances = 10× the transistors and power. Unlike a function call that reuses the same CPU, there's no sharing. |
| Flip-flop | "Like a staging table that refreshes on a schedule" | A flip-flop is a physical bistable circuit — two cross-coupled gates that hold a voltage. It captures input ONLY at the clock edge. Between edges, it ignores input entirely. Violate setup/hold timing → the circuit enters a metastable state (physically indeterminate — neither 0 nor 1) with no software equivalent. |
| Clock | "Like a cron job ticking at fixed intervals" | The clock is a physical oscillator (crystal on the board vibrating). It doesn't "trigger" things like a scheduler — it provides the snapshot boundary between combinational settling and state capture. Between clock edges, all combinational logic is continuously computing and settling (with glitches). The clock frequency is physically limited by the longest gate chain (critical path). |
| Mux / sel | "Like an if/switch picking which value to output" | A mux is a physical circuit made of gates, always present and always computing all inputs simultaneously. The sel input electrically steers which input reaches the output. Unlike if/else, there are no "branches not taken" — all paths exist in hardware. |
always @(*) | "Like a reactive/computed expression" | This describes combinational logic — a stateless circuit whose output depends only on current inputs, like a pure function. BUT: it settles through real propagation delay (picoseconds per gate), and during settling, outputs may glitch to wrong values temporarily. |
always @(posedge clk) | "Like a scheduled batch update" | ALL clocked always blocks fire at the exact same instant (the clock edge). This is why <= exists — it reads old values first, then all registers update simultaneously. This models the physical reality of all flip-flops latching at once. |
for loop | "Like a loop that runs N times" | A for loop doesn't iterate — it replicates N copies of the circuit in parallel. for(i=0; i<8; i++) creates 8 physical instances of whatever's inside. |
Vector [7:0] | "Like a fixed-width integer" | It's 8 parallel wires, each carrying one bit simultaneously. Operations on vectors happen on all bits at once in hardware. |
9c. The 7 Killer Misconceptions to Watch For
These are the most dangerous beliefs software engineers bring. Probe for them actively when you see related symptoms:
| # | Misconception | Why it's dangerous | How to correct |
|---|---|---|---|
| 1 | "Code runs top to bottom" | All always blocks and assign statements are concurrent. This causes ~40% of beginner bugs. | "All your assign/always blocks run simultaneously. Reorder them — the circuit doesn't change." |
| 2 | "Blocking = vs <= is style" | = in clocked blocks creates race conditions that are simulation-order dependent — appears to work, silently broken. | "In a clocked block, <= reads all old values first, then updates all at once. = updates immediately and the next line sees the new value — order now matters, which is wrong for hardware." |
| 3 | "If without else = no-op" | Synthesizes an unintentional latch — the #1 cause of "works in sim, fails in hardware." | "In combinational logic, if you don't specify a value in every branch, the tool must remember the old value → latch. Always cover every case." |
| 4 | "reg = register" | Historical misnomer. reg only becomes a flip-flop inside always @(posedge clk). In combinational blocks it's just a wire. | "Ignore the name. reg means 'can be assigned in a procedural block.' Whether it becomes a flip-flop depends on context." |
| 5 | "Operations are free" | Every operation is a physical gate. More logic = more area = slower critical path = lower max frequency. | "What gates does this multiply become? How many of those can you afford?" |
| 6 | "Simulation pass = correct" | Glitches, metastability, and clock-domain crossing bugs are invisible in RTL simulation by design. | Surface this when relevant — not yet at HDLBits level, but plant the seed. |
| 7 | "I can refactor freely" | Moving code between always blocks changes inferred hardware topology. | "Which hardware block does each always block become? Moving logic between them changes the circuit." |
9d. Hardware-Native Mental Models to Build Over Time
The goal is to gradually shift the student from software thinking to these hardware-native frames:
1. Schematic thinking — "If you can't draw the circuit, you can't code it." Before writing Verilog, picture boxes (modules, gates, flip-flops) and wires. 2. Two-world model — There are only two kinds of hardware:
- Combinational (stateless, always settling, like a pure function)
- Sequential (stateful, updates only at clock edge)
The clock edge is the boundary between them. Every design is just these two worlds connected together. 3. Waveform thinking — Describe behavior as signals over time, not as code execution. Timing diagrams are the native language of hardware. 4. Synthesis awareness — For every construct, ask: "What gates and flip-flops does this become?" 5. Concurrency as default — In software, you coordinate concurrency. In hardware, you coordinate sequencing. The discipline is inverted.
Surface these gradually — one insight per exercise when context makes it natural. Don't lecture.
9e. Tone
- Patient. First-time hardware learner.
- Concise. One question per turn. Don't dump all hint levels at once.
- Encouraging but honest. Celebrate correct answers; name
misunderstandings clearly, then fix them together.
- No code dumps. Redirect to the next hint level and explain why
understanding matters.
- Ground jargon before using it. Don't say "rising edge" without first
explaining "when clock goes 0→1." Don't say "combinational" without "stateless — output depends only on current inputs."
---
10. Quick-Reference Cheat Sheet
Read exercise → hdlbits_exercise <slug> | read exercises/<cat>/<slug>.v
Run grader → hdlbits_run <slug> | ./hdlbits run <slug>
Get hint → hdlbits_hint <slug> | ./hdlbits hint <slug>
Next exercise → hdlbits_next | ./hdlbits next
List all → hdlbits_progress | ./hdlbits list
Hint ladder: Conceptual → Structural → Near-answer → one construct
Error classes: Compile | Incorrect | Timeout
Key mistakes: sensitivity list · blocking/non-blocking · missing default ·
bit-width · combinational loop · missing endmodule
Always close: "Why does this work?"HDLBits Categories Knowledge Map
A reference map of all 20 HDLBits categories — concepts taught, required skills, pitfalls, and prerequisites.
---
00 · Getting Started (2 exercises)
Concepts: HDLBits interface, module structure, basic wire output. Key Skills: Write a minimal module; connect a constant or wire to an output. Pitfalls: Forgetting the endmodule keyword; not matching the given module signature. Prerequisites: None.
---
01 · Verilog Language > Basics (8 exercises)
Concepts: wire, assign, simple Boolean gates (AND, OR, NOT, XOR, NAND, etc.), module ports. Key Skills: Continuous assignment; combining gates with assign; port declarations. Pitfalls: Operator precedence (use parentheses); ~ vs !; forgetting output declarations. Prerequisites: 00 Getting Started.
---
02 · Verilog Language > Vectors (9 exercises)
Concepts: Multi-bit vectors, part-select [i:j], concatenation {}, replication {N{x}}, bitwise vs reduction operators. Key Skills: Slicing and joining bit vectors; sign extension; byte reversal. Pitfalls: Wrong bit-order in part-select; replication syntax {N{expr}} (not N*expr); mixing vector widths in assignments. Prerequisites: 01 Basics.
---
03 · Verilog Language > Modules (9 exercises)
Concepts: Module instantiation, named vs positional port connections, hierarchical design, port direction. Key Skills: Instantiate provided submodules; wire them together; handle dangling/unused ports. Pitfalls: Positional port order errors; driving an input port from the wrong direction; leaving outputs unconnected. Prerequisites: 01 Basics, 02 Vectors.
---
04 · Verilog Language > Procedures (8 exercises)
Concepts: always @(*) (combinational), always @(posedge clk) (sequential), blocking = vs non-blocking <=, if/else, case. Key Skills: Choose correct always-block type; use correct assignment style; avoid latches. Pitfalls: Using blocking assignment in sequential blocks; missing default/else causes latches; reg vs wire type for driven signals. Prerequisites: 01 Basics, 02 Vectors.
---
05 · Verilog Language > More Features (7 exercises)
Concepts: casez / casex, conditional ? :, generate/genvar, parameter, $signed, arithmetic operators. Key Skills: Priority logic with casez; parameterized designs; signed arithmetic and shifts. Pitfalls: Forgetting $signed for arithmetic right shift; generate block naming; parameter override syntax. Prerequisites: 04 Procedures.
---
06 · Circuits > Combinational > Basic Gates (17 exercises)
Concepts: Universal gates, multi-input logic, truth tables → Verilog, wire functions, tristate buffers. Key Skills: Translate any truth table to assign statements; NAND/NOR/XNOR; gates with many inputs. Pitfalls: Reduction operators (&in, |in) vs bitwise; off-by-one in bit indexing; tri-state buz types. Prerequisites: 01 Basics, 02 Vectors.
---
07 · Circuits > Combinational > Multiplexers (5 exercises)
Concepts: 2:1, 4:1, wider muxes; priority mux; mux-based logic functions. Key Skills: Build muxes with ternary operator and case; use muxes to implement arbitrary functions. Pitfalls: Missing default in case mux (latch!); one-hot select decoding errors. Prerequisites: 04 Procedures, 06 Basic Gates.
---
08 · Circuits > Combinational > Arithmetic (7 exercises)
Concepts: Adders, subtractors, carry-lookahead concepts, overflow detection, comparators, BCD addition. Key Skills: Bit-width management in addition; signed overflow; chaining adder modules. Pitfalls: Carry-out bit lost if output register is too narrow; signed vs unsigned overflow differ; BCD carry conditions. Prerequisites: 02 Vectors, 03 Modules.
---
09 · Circuits > Combinational > Karnaugh Maps (8 exercises)
Concepts: K-map minimization, SOP/POS forms, don't-cares, multi-output minimization. Key Skills: Read a K-map or truth table; write minimized Boolean expression as assign. Pitfalls: Grouping errors (groups must be power-of-2 size); missing don't-cares as minimization aids; wrong variable ordering. Prerequisites: 01 Basics, 06 Basic Gates.
---
10 · Circuits > Sequential > Flip-Flops (18 exercises)
Concepts: D-FF, T-FF, JK-FF, SR latch, synchronous/asynchronous reset, clock enable, edge detection, DFF arrays. Key Skills: Instantiate and build flip-flops; manage reset polarity; detect rising/falling edges. Pitfalls: Async reset belongs in sensitivity list; active-high vs active-low reset confusion; edge detector needs two registers. Prerequisites: 04 Procedures.
---
11 · Circuits > Sequential > Counters (8 exercises)
Concepts: Binary up/down counters, decade counters, arbitrary modulo counters, slow-clock dividers. Key Skills: Synchronous load and reset; terminal count detection; clock dividers. Pitfalls: Off-by-one on terminal count; counter not resetting properly; slow-clock enable vs actual slow clock. Prerequisites: 10 Flip-Flops.
---
12 · Circuits > Sequential > Shift Registers (9 exercises)
Concepts: SIPO/PISO shift registers, LFSRs, Galois LFSR, barrel shifter, rotate. Key Skills: Shift left/right with concatenation; LFSR tap polynomial; parallel load vs serial shift. Pitfalls: Wrong shift direction; LFSR tap positions (check polynomial); confusing rotate with shift. Prerequisites: 10 Flip-Flops, 02 Vectors.
---
13 · Circuits > Sequential > More Circuits (3 exercises)
Concepts: Ring counters, Johnson counters, sequence detectors without explicit FSM. Key Skills: Creative reuse of shift register structures; recognizing patterns in bit sequences. Pitfalls: Johnson counter output decoding; ensuring correct initial state for ring/Johnson counters. Prerequisites: 11 Counters, 12 Shift Registers.
---
14 · Circuits > Sequential > Finite State Machines (34 exercises)
Concepts: Moore vs Mealy FSMs, state encoding, sequence detectors, string recognizers, complex controllers. Key Skills: Two/three always-block FSM style; one-hot encoding; overlapping vs non-overlapping sequences. Pitfalls: Missing default state (latch or X); Mealy output not responding to input immediately; state never transitions out of reset; confusing Moore/Mealy output placement. Prerequisites: 10 Flip-Flops, 04 Procedures.
---
15 · Circuits > Building Larger Circuits (7 exercises)
Concepts: Combining counters, shift registers, FSMs, and datapath components into larger systems. Key Skills: Hierarchical instantiation; coordinating control + datapath; timing across modules. Pitfalls: Control/datapath timing mismatches; forgetting to connect all sub-module resets; bus width mismatches between modules. Prerequisites: 11 Counters, 12 Shift Registers, 14 FSMs.
---
16 · Verification > Finding Bugs (5 exercises)
Concepts: Identifying bugs in given (broken) Verilog code — logic errors, wrong operators, missing bits. Key Skills: Code reading; tracing signal flow; spotting subtle type and operator errors. Pitfalls: Assuming the code is mostly correct — the bug may be a single wrong character or operator. Prerequisites: All language + combinational categories.
---
17 · Verification > Simulation Waveforms (10 exercises)
Concepts: Reading waveform diagrams and writing Verilog that matches the shown behavior exactly. Key Skills: Translating waveform timing to procedural stimulus; initial blocks; #delay. Pitfalls: Off-by-one clock cycle; not matching exact signal transitions shown; forgetting to $finish. Prerequisites: 04 Procedures, familiarity with sequential behavior.
---
18 · Verification > Writing Testbenches (5 exercises)
Concepts: Full testbench authoring: clock gen, reset, stimulus sequences, checking outputs. Key Skills: initial/always for clocks; applying vectors; $display/$monitor; task definitions. Pitfalls: Clock never toggles (missing always #N); stimulus applied at exactly the clock edge (use small #delay); no $finish causes infinite simulation. Prerequisites: 04 Procedures, 17 Simulation Waveforms.
---
19 · CS450 (4 exercises)
Concepts: Advanced: pipelined CPU datapath fragments, hazard detection, forwarding units (university course problems). Key Skills: Multi-stage pipeline reasoning; hazard/forwarding logic; complex conditional assignments. Pitfalls: Conflating pipeline stages; incorrect forwarding conditions; register file read/write ordering. Prerequisites: All prior categories, especially 14 FSMs and 15 Building Larger Circuits.
HDLBits Error Diagnosis & Fix Guide
Reading HDLBits Error Output
"Hint: output X has Y values that differ"
Your module compiled and simulated, but produced wrong signal values.
- Y values = number of simulation timesteps where your output ≠ expected.
- Check the waveform viewer: compare your output row vs. the reference row.
- Red/mismatched sections show exactly when the divergence occurs.
Compile Error Panel
Shown before simulation. Fix these first — no waveform is generated until the design compiles.
---
Compile Errors
Syntax Errors
Error: near "endmodule": syntax error- Missing
;at end ofassign, port declaration, or statement. - Mismatched
begin/end— everybeginneeds a matchingend. always @block missing sensitivity list or body.- Fix: Read upward from the reported line — the real error is often a few lines above.
Undeclared Wire / Reg
Error: 'foo' is not declared- Signal used but never declared (
wire,reg, or input/output). - Typo in signal name (Verilog is case-sensitive:
Out≠out). - Fix: Declare all internal signals; verify exact spelling.
Port Mismatch
Error: port width mismatch — expected 4 bits, got 1- Connecting a scalar to a vector port or vice versa.
- HDLBits top-level port widths are fixed by the problem spec.
- Fix: Ensure your port declarations match the problem's module signature exactly.
Mismatched begin/end
Error: syntax error near 'else'- An
ifbody with multiple statements but nobegin/end. - Fix: Wrap multi-statement bodies in
begin ... end.
---
Incorrect Results (Wrong Logic)
Wrong Boolean Logic
- Verify operator precedence:
&binds tighter than|; use parentheses. ~is bitwise NOT;!is logical NOT (returns 1 bit). Mix-up causes subtle bugs.
Off-by-One in Counters
- Counter reaches
Ninstead of stopping atN-1: check== Nvs== N-1. - BCD counter: boundary condition must be
count == 9, notcount == 10.
Missing Reset / Initial State
- Flip-flop outputs are
x(unknown) at simulation start without reset. - Fix: Always handle
reset(orareset) to drive outputs to a known value.
Wrong Bit Ordering
- HDLBits uses
[MSB:LSB](e.g.,[3:0]). Reversing to[0:3]is legal but unusual and causes confusion. - Part-select reversal:
byte[0:3]≠byte[3:0].
Unsigned vs Signed Arithmetic
- By default, Verilog operands are unsigned.
$signed(in) >>> 1for arithmetic right shift;in >> 1is logical (fills with 0).- Comparisons:
8'hFF > 8'h01is true unsigned, but if both are$signed,8'hFF= -1 < 1.
Blocking vs Non-Blocking in Sequential Logic
- Using
=(blocking) instead of<=(non-blocking) in clockedalwaysblocks creates order-dependent behavior. - Fix: Use
<=in allalways @(posedge clk)blocks; use=inalways @(*)blocks.
---
Simulation / Structural Errors
Combinational Loops
Warning: combinational loop detected on signal 'out'- A signal feeds back into its own combinational logic without a register.
- Simulation may hang or produce X values.
- Fix: Break the loop with a register (flip-flop) or redesign the logic.
Inferred Latches (Missing Default / Else)
Warning: latch inferred for signal 'out'- A combinational
always @(*)block does not assignoutin every code path. - HDLBits treats latches as incorrect unless the problem specifically asks for one.
- Fix: Add a
defaultto everycase, and anelseto everyifin combinational blocks.
Timing / Edge Issues in Testbenches
- Sampling outputs exactly at the clock edge can catch a value mid-transition.
- Fix: Sample outputs a small
#delayafterposedge clk, or use non-blocking reads.
---
Common Gotchas by Category
| Category | Typical Mistake |
|---|---|
| Basics | Wrong operator; missing port in module header |
| Vectors | Bit-select out of range; wrong replication syntax {N{x}} |
| Modules | Port direction wrong (input vs output); unconnected ports left floating |
| Procedures | Using assign inside always, or <= in combinational block |
| More Features | Forgetting $signed for signed ops; wrong generate syntax |
| Flip-Flops | Async vs sync reset mixed up; missing enable path |
| Counters | Off-by-one; counter doesn't reset on terminal count |
| Shift Registers | Shift direction reversed; LFSR tap positions wrong |
| FSMs | Missing default state; Mealy outputs not updated on input change; state never reaches accepting state |
| Karnaugh Maps | Grouping errors; not minimizing fully; wrong SOP/POS form |
| Verification | Testbench clock not toggling; stimulus applied before reset deasserts |
Pedagogy Research Notes for HDLBits Tutor
This note records the research basis for the local HDLBits tutor policy.
Sources
1. Hattie, J., & Timperley, H. (2007). The Power of Feedback. Review of Educational Research. Link: https://journals.sagepub.com/doi/10.3102/003465430298487
2. Wisniewski, B., Zierer, K., & Hattie, J. (2020). The Power of Feedback Revisited: A Meta-Analysis of Educational Feedback Research. Frontiers in Psychology. Link: https://www.frontiersin.org/journals/psychology/articles/10.3389/fpsyg.2019.03087/full
3. Kirschner, P. A., Sweller, J., & Clark, R. E. (2006). Why Minimal Guidance During Instruction Does Not Work. Educational Psychologist. Link: https://www.sfu.ca/~jcnesbit/EDUC220/ThinkPaper/KirschnerSweller2006.pdf
4. Kalyuga, S. (2007). Expertise Reversal Effect and Its Implications for Learner-Tailored Instruction. Educational Psychology Review. Link: https://link.springer.com/article/10.1007/s10648-007-9054-3
5. Salden, R. J. C. M., Aleven, V., Schwonke, R., & Renkl, A. (2010). The Expertise Reversal Effect and Worked Examples in Tutored Problem Solving. Educational Psychology Review. Link: https://www.cs.cmu.edu/afs/cs/Web/People/bmclaren/pubs/SaldenEtAl-BeneficialEffectsWorkedExamplesinTutoredProbSolving-EdPsychRev2010.pdf
6. Shubeck, K., Fang, Y., Hampton, A., Morgan, B., Hu, X., & Graesser, A. (2018). Embedding effective teaching strategies in intelligent tutoring systems. Link: https://digitalcommons.memphis.edu/facpubs/19192/
Policy Implications
- For novices, stronger guidance beats forced discovery.
- Feedback should be task-focused and process-focused, not generic praise.
- Worked examples are useful when the learner is blocked on syntax or a specific step.
- Guidance should adapt as the learner improves.
- A fixed tutoring style is inferior to learner-aware scaffolding.
Implementation Mapping
tutor-policy.mdcontains the operational rules used by the local tutor..pi/extensions/hdlbits-tutor.tsinjects that policy into the Pi session.SKILL.mdpoints to the same local policy so the skill and runtime extension do not drift.
HDLBits Tutor Policy
This file is the local source of truth for the HDLBits tutor behavior in this repository.
Research Basis
This policy is grounded in a small set of stable tutoring findings:
- Novices benefit from stronger guidance than minimal-discovery instruction.
- Feedback is most useful when it is specific, timely, and tied to the task or process rather than generic praise.
- Worked examples and tiny step demonstrations reduce unnecessary cognitive load for beginners.
- Guidance should fade as learner expertise increases.
- Effective ITS behavior must adapt to learner state and domain state, not just follow one fixed tutoring style.
Key sources:
- Kirschner, Sweller, and Clark (2006), "Why Minimal Guidance During Instruction Does Not Work"
- Hattie and Timperley (2007), "The Power of Feedback"
- Wisniewski, Zierer, and Hattie (2020), "The Power of Feedback Revisited"
- Kalyuga (2007), "Expertise Reversal Effect and Its Implications for Learner-Tailored Instruction"
- Salden et al. (2010), "The Expertise Reversal Effect and Worked Examples in Tutored Problem Solving"
- Shubeck et al. (2018), "Embedding effective teaching strategies in intelligent tutoring systems"
Default Behavior
- Be direct-first.
- Answer definitions, syntax, and notation questions plainly.
- Use questions only after the concept is grounded.
- If the student is confused twice in a row, reduce questioning and increase explanation clarity.
- Prefer one tiny worked example over multiple abstract prompts.
- Point out the exact misunderstanding before asking for another step.
- Inspect the file the student points to before asking for more context.
- Keep responses concise, but never vague.
- Use exact Verilog syntax and explain notation explicitly.
- If the student is stuck on syntax or notation, show the pattern, then one minimal example.
- If you are unsure, say so and verify instead of guessing.
- Prefer task/process feedback over praise about the learner.
- Avoid filler praise and personality-level feedback.
- Do not use celebratory phrases like "well done", "great job", or "awesome".
- Increase guidance for novice confusion; reduce guidance only when the learner shows stable understanding.
Response Shape
1. What it means 2. Why it matters 3. Tiny example 4. Your next step
Escalation Ladder
1. Direct clarification 2. Structural hint 3. Near-answer 4. Single corrected construct with explanation
Manual Test Scenarios
These are the local checks the tutor should pass.
Scenario 1: Syntax clarification
User: what does 3'd1 mean?
Expected behavior:
- Explain the sized-number syntax directly.
- Show one tiny example.
- Ask at most one short check question.
Scenario 2: Confused follow-up
User: wait what even is 3:d1?
Expected behavior:
- Clarify the notation directly.
- Correct the mistaken syntax.
- Do not chain multiple questions.
Scenario 3: Asking for code review
User: is my answer correct? and points to a file.
Expected behavior:
- Inspect the file they pointed to before asking for more context.
- Say what is correct and what is not.
- Prefer one concrete correction over vague hints.
Scenario 4: Repeated confusion
User asks two related questions and still does not understand.
Expected behavior:
- Reduce questioning.
- Increase explanation clarity.
- Use a tiny worked example instead of another abstract prompt.
Verilog Patterns & Idioms Reference
Wire Assignments
Continuous Assignment
assign out = a & b; // AND gate
assign out = ~in; // inverter
assign out = a ? b : c; // ternary (mux)
assign out = a ^ b ^ cin; // XOR chainUse assign for combinational logic on wire types. Evaluated continuously.
Multiple Drivers (avoid)
A wire may only have one driver. Multiple assign statements to the same wire cause compile errors.
---
Always Blocks
Combinational (always @(*))
always @(*) begin
out = a & b; // no clock; use blocking assignment (=)
endUse * to auto-infer sensitivity list. Missing signals in the list cause latches.
Clocked / Sequential (always @(posedge clk))
always @(posedge clk) begin
q <= d; // non-blocking assignment (<=) for flip-flops
endNon-blocking (<=) prevents race conditions in clocked blocks. Always use it for sequential logic.
---
If / Case / Casez
If-Else
always @(*) begin
if (sel)
out = a;
else
out = b;
endAlways provide an else branch in combinational blocks to avoid unintended latches.
Case
always @(*) begin
case (sel)
2'b00: out = a;
2'b01: out = b;
2'b10: out = c;
default: out = d; // required to avoid latches
endcase
endCasez (don't-care bits with ? or z)
always @(*) begin
casez (in)
4'b1???: out = 3;
4'b01??: out = 2;
4'b001?: out = 1;
default: out = 0;
endcase
end? matches 0, 1, or x/z. Useful for priority encoders.
---
Module Instantiation
Named Port Connection (preferred)
mod_name u1 (
.port_a(sig_a),
.port_b(sig_b),
.out(result)
);Positional Port Connection
mod_name u1 (sig_a, sig_b, result);Positional is error-prone for modules with many ports. Named ports are safer.
---
Vectors
Declaration & Part Select
wire [7:0] byte; // 8-bit vector [MSB:LSB]
assign nibble = byte[7:4]; // upper nibble
assign bit3 = byte[3]; // single bitConcatenation {}
assign {cout, sum} = a + b + cin; // split result
assign word = {high_byte, low_byte}; // join bytesReplication {N{x}}
assign sign_ext = {{24{in[7]}}, in}; // sign-extend 8→32 bits
assign zeros = {8{1'b0}}; // 8 zero bits---
Flip-Flops
Basic D Flip-Flop
always @(posedge clk) q <= d;Synchronous Reset
always @(posedge clk) begin
if (reset) q <= 0;
else q <= d;
endAsynchronous Reset
always @(posedge clk or posedge reset) begin
if (reset) q <= 0;
else q <= d;
endReset in the sensitivity list = asynchronous; only in the body = synchronous.
D FF with Enable
always @(posedge clk) begin
if (en) q <= d;
// no else: q retains value (that's the enable behavior)
end---
Counters
Binary Counter
always @(posedge clk) begin
if (reset) count <= 0;
else count <= count + 1;
endDecade Counter (0–9)
always @(posedge clk) begin
if (reset || count == 9) count <= 0;
else count <= count + 1;
endBCD Counter (multi-digit)
// ones digit rolls at 9, tens digit increments then
always @(posedge clk) begin
if (reset) begin ones <= 0; tens <= 0; end
else if (ones == 9) begin
ones <= 0;
tens <= (tens == 9) ? 0 : tens + 1;
end else ones <= ones + 1;
end---
Shift Registers
Basic Serial-In Shift Register
always @(posedge clk) begin
q <= {q[N-2:0], serial_in}; // shift left, insert at LSB
endLFSR (example: 4-bit, taps 3,0)
always @(posedge clk) begin
q <= {q[2:0], q[3] ^ q[0]};
endBarrel Shifter (combinational)
assign out = in >> shift_amt; // logical right shift
assign out = in << shift_amt; // logical left shift
assign out = $signed(in) >>> shift_amt; // arithmetic right shift---
FSM Patterns
Moore FSM (output depends only on state)
// Two always blocks: state register + next-state/output logic
parameter S0=0, S1=1, S2=2;
reg [1:0] state;
always @(posedge clk) begin
if (reset) state <= S0;
else state <= next_state;
end
always @(*) begin
case (state)
S0: begin next_state = in ? S1 : S0; out = 0; end
S1: begin next_state = in ? S2 : S0; out = 0; end
S2: begin next_state = S0; out = 1; end
default: begin next_state = S0; out = 0; end
endcase
endMealy FSM (output depends on state + inputs)
always @(*) begin
case (state)
S0: begin
out = (in) ? 1 : 0; // output depends on input
next_state = in ? S1 : S0;
end
default: begin out = 0; next_state = S0; end
endcase
endOne-Hot Encoding
parameter S0 = 3'b001, S1 = 3'b010, S2 = 3'b100;
reg [2:0] state;One-hot uses 1 bit per state; faster decoding but more flip-flops.
---
Generate / For-Loop Patterns
genvar i;
generate
for (i = 0; i < 8; i = i+1) begin : gen_block
assign out[i] = a[i] ^ b[i];
end
endgenerateUse generate for repetitive structural instantiation or assignments.
---
Testbench Patterns
Clock Generation
initial clk = 0;
always #5 clk = ~clk; // 10-unit periodReset + Stimulus
initial begin
reset = 1; d = 0;
@(posedge clk); #1;
reset = 0;
d = 1; @(posedge clk); #1;
d = 0; @(posedge clk); #1;
$finish;
endApply inputs slightly after the clock edge (#1) to avoid setup issues.