Tasks - Simplifying Repetitve Code

Motivation

When writing software, some operations, whilst simple in concept and maths require large quantities of code to perform. This operation may be required more than once in a program. Including long procedures in the main of a program, espeicially if repeated, detracts from the flow, readability and de-bugging ease. To this end Verilog supports Tasks and Functions.


Tasks

Within a behavioural model many lines of code can be grouped together and called anywhere from in that module. This is a task.

Tasks are used in all programming languages, generally known as Procedures or sub routines (SUBs). Many lines of code are enclosed in task....end task brackets. Data is passed to the task, the processing done, and the result returned to a specified value. They have to be specifically called, with data in and outs, rather than just “wired in” to the general netlist. Included in the main body of code they can be called many times, reducing code repitition.


Syntax

Example of use

Consider the trivial example below. A thermometer module displays the value it contains, converting the reading from Celcius to Farhenheit; making use of the task Convert.
  • The variables declared within the task are local to that task. The order of declaration within the task defines how the variables passed to the task by the caller are used.
  • A task must be specifically called with a statement, it cannot be used within an expression as a function can.

  • All the processing of a task must be within begin_end calls, including final declarations to outputs. Timing, delay, and event functions may be used within tasks

  • Tasks may invoke other tasks, themselves or functions.

  • To call a task the main module uses the name of the task as a complete statement, with variables being in brackets after cf

    [Task_name]([variable list]);

    The task then copies the variables into its own local variables, performs the action and writes data directly back into the specified original variables. The above example does not require any further mention of the variable Temperature' as the task 'convert' directly changes it. Care must therefore be taken to ensure that the variable 'Temperature' is of a type that can be written to. An input for example is not, and would cause and error.