2.1 A basic MyHDL simulation

We will introduce MyHDL with a classic Hello World style example. All example code can be found in the distribution directory under example/manual/. Here are the contents of a MyHDL simulation script called hello1.py:

from myhdl import Signal, delay, always, now, Simulation

def HelloWorld():

    interval = delay(10)
    
    @always(interval)
    def sayHello():
        print "%s Hello World!" % now()

    return sayHello


inst = HelloWorld()
sim = Simulation(inst)
sim.run(30)

When we run this simulation, we get the following output:

% python hello1.py
10 Hello World!
20 Hello World!
30 Hello World!
_SuspendSimulation: Simulated 30 timesteps

The first line of the script imports a number of objects from the myhdl package. In Python we can only use identifiers that are literally defined in the source file 2.1.

Then, we define a function called HelloWorld. In MyHDL, classic functions are used to model hardware modules. In particular, the parameter list is used to define the interface. In this first example, the interface is empty.

Inside the top level function we declare a local function called sayHello that defines the desired behavior. This function is decorated with an always decorator that has a delay  object as its parameter. The meaning is that the function will be executed whenever the specified delay interval has expired.

Behind the curtains, the always decorator creates a Python generator and reuses the name of the decorated function for it. Generators are the fundamental objects in MyHDL, and we will say much more about them further on.

Finally, the top level function returns the local generator. This is the simplest case of the basic MyHDL code pattern to define the contents of a hardware module. We will describe the general case further on.

In MyHDL, we create an instance of a hardware module by calling the corresponding function. In the example, variable inst refers to an instance of HelloWorld. To simulate the instance, we pass it as an argument to a Simulation object constructor. We then run the simulation for the desired amount of timesteps.



Footnotes

... file2.1
The exception is the "from module import *" syntax, that imports all the symbols from a module. Although this is generally considered bad practice, it can be tolerated for large modules that export a lot of symbols. One may argue that myhdl falls into that category.
About this document