0
# Cocotb
1
2
A coroutine-based cosimulation library for writing VHDL and Verilog testbenches in Python. Cocotb enables hardware verification engineers to create comprehensive test suites using Python's rich ecosystem, providing seamless integration with various HDL simulators including Icarus Verilog, Verilator, GHDL, Questa, and others.
3
4
## Package Information
5
6
- **Package Name**: cocotb
7
- **Language**: Python
8
- **Installation**: `pip install cocotb`
9
10
## Core Imports
11
12
```python
13
import cocotb
14
```
15
16
Common imports for testbench development:
17
18
```python
19
import cocotb
20
from cocotb.decorators import test, coroutine
21
from cocotb.triggers import Timer, RisingEdge, FallingEdge, Edge
22
from cocotb.clock import Clock
23
```
24
25
## Basic Usage
26
27
```python
28
import cocotb
29
from cocotb.triggers import Timer, RisingEdge
30
from cocotb.clock import Clock
31
32
@cocotb.test()
33
async def basic_test(dut):
34
"""Basic testbench demonstrating clock generation and signal monitoring."""
35
36
# Start a clock
37
clock = Clock(dut.clk, 10, units="ns")
38
cocotb.start_soon(clock.start())
39
40
# Reset sequence
41
dut.reset.value = 1
42
await Timer(100, units="ns")
43
dut.reset.value = 0
44
45
# Wait for clock edge and test functionality
46
await RisingEdge(dut.clk)
47
dut.input_signal.value = 0xAB
48
49
# Wait a few clock cycles and check output
50
for _ in range(5):
51
await RisingEdge(dut.clk)
52
53
assert dut.output_signal.value == 0xAB, f"Expected 0xAB, got {dut.output_signal.value}"
54
55
# Test completion
56
await Timer(50, units="ns")
57
58
@cocotb.test()
59
async def concurrent_test(dut):
60
"""Example showing concurrent task execution."""
61
62
# Start multiple concurrent tasks
63
task1 = cocotb.start_soon(stimulus_generator(dut))
64
task2 = cocotb.start_soon(response_monitor(dut))
65
66
# Wait for completion
67
await task1
68
await task2
69
70
async def stimulus_generator(dut):
71
"""Generate stimulus signals."""
72
for i in range(10):
73
dut.data_in.value = i
74
await Timer(20, units="ns")
75
76
async def response_monitor(dut):
77
"""Monitor response signals."""
78
for i in range(10):
79
await RisingEdge(dut.clk)
80
cocotb.log.info(f"Output: {dut.data_out.value}")
81
```
82
83
## Architecture
84
85
Cocotb's architecture centers around coroutines and event-driven simulation:
86
87
- **Test Framework**: Python decorators mark test functions, with automatic discovery and execution
88
- **Coroutine System**: Async/await syntax for simulation time management and concurrency
89
- **Trigger System**: Event-based synchronization with simulator (time, edges, custom events)
90
- **Handle System**: Hierarchical access to HDL design objects with type-appropriate interfaces
91
- **Task Management**: Concurrent execution of multiple coroutines with join/kill capabilities
92
- **Simulator Interface**: GPI (Generic Programming Interface) provides simulator abstraction
93
94
This design enables Python-native testbench development while maintaining tight integration with HDL simulators, allowing engineers to leverage Python's extensive libraries for test data generation, analysis, and reporting.
95
96
## Capabilities
97
98
### Test Framework
99
100
Core decorators and functions for defining and running tests, including test discovery, execution control, timeout handling, and result management.
101
102
```python { .api }
103
@test(timeout_time=None, timeout_unit="step", expect_fail=False, expect_error=(), skip=False, stage=0)
104
def test_decorator(func): ...
105
106
@coroutine
107
def coroutine_decorator(func): ...
108
109
@external
110
def external_decorator(func): ...
111
```
112
113
[Test Framework](./test-framework.md)
114
115
### Task Management
116
117
Functions for creating, scheduling, and managing concurrent coroutines including immediate scheduling, yielding execution, task creation, and the deprecated fork function.
118
119
```python { .api }
120
def start_soon(coro: Union[Task, Coroutine]) -> Task: ...
121
async def start(coro: Union[Task, Coroutine]) -> Task: ...
122
def create_task(coro: Union[Task, Coroutine]) -> Task: ...
123
def fork(coro: Union[Task, Coroutine]) -> Task: ... # DEPRECATED
124
```
125
126
[Task Management](./task-management.md)
127
128
### Triggers and Timing
129
130
Comprehensive trigger system for time-based and event-based synchronization including timers, signal edges, composite triggers, and synchronization primitives.
131
132
```python { .api }
133
class Timer(time, units="step", round_mode=None): ...
134
class RisingEdge(signal): ...
135
class FallingEdge(signal): ...
136
class Edge(signal): ...
137
class Event(): ...
138
class Lock(): ...
139
```
140
141
[Triggers and Timing](./triggers-timing.md)
142
143
### Signal Handling
144
145
Design object access through hierarchical handles supporting reads, writes, forcing, and comprehensive signal manipulation across different HDL types.
146
147
```python { .api }
148
class SimHandleBase: ...
149
class HierarchyObject(SimHandleBase): ...
150
class ModifiableObject(NonConstantObject): ...
151
def SimHandle(handle, path=None): ...
152
```
153
154
[Signal Handling](./signal-handling.md)
155
156
### Clock Generation
157
158
Clock generation utilities for creating periodic signals with configurable periods, duty cycles, and phase relationships.
159
160
```python { .api }
161
class Clock(signal, period, units="step"): ...
162
class BaseClock: ...
163
```
164
165
[Clock Generation](./clock-generation.md)
166
167
### Binary and Type System
168
169
Binary value representation and HDL-compatible types including logic values, arrays, ranges, and conversion utilities.
170
171
```python { .api }
172
class BinaryValue(value=None, n_bits=None, bigEndian=True, binaryRepresentation=BinaryRepresentation.UNSIGNED): ...
173
class Logic: ...
174
Bit = Logic # Type alias
175
class LogicArray: ...
176
class Array[T]: ...
177
class Range(left, direction, right): ...
178
```
179
180
[Binary and Type System](./binary-types.md)
181
182
### Logging and Utilities
183
184
Simulation-aware logging, time utilities, queue implementations, and debugging support with simulation time context and hierarchical naming.
185
186
```python { .api }
187
class SimLog: ...
188
def get_sim_time(units="step"): ...
189
def get_sim_steps(time, units, round_mode=None): ...
190
class Queue[T](maxsize=0): ...
191
```
192
193
[Logging and Utilities](./logging-utilities.md)
194
195
## Global Variables
196
197
```python { .api }
198
scheduler: Optional[Scheduler] # Global scheduler instance
199
regression_manager: Optional[RegressionManager] # Global regression manager
200
top: Optional[SimHandleBase] # Handle to toplevel entity/module (DUT)
201
argv: Optional[List[str]] # Simulator argument list
202
argc: Optional[int] # Length of argv
203
plusargs: Optional[Dict[str, Union[bool, str]]] # Simulator plusargs
204
LANGUAGE: Optional[str] # TOPLEVEL_LANG environment variable
205
SIM_NAME: Optional[str] # Running simulator product name
206
SIM_VERSION: Optional[str] # Running simulator version
207
RANDOM_SEED: Optional[int] # Random number generator seed
208
__version__: str # Cocotb version string
209
```
210
211
## Types
212
213
```python { .api }
214
from typing import Union, Optional, List, Dict, Any, Coroutine
215
from collections.abc import Coroutine
216
217
# Core types
218
Task = cocotb.task.Task
219
SimHandleBase = cocotb.handle.SimHandleBase
220
221
# Union type for coroutine parameters
222
CoroutineType = Union[Task, Coroutine]
223
```