Timers: Prescaler, Compare, Capture and PWM

A pin must be high for a quarter of the time. Another pin must be dated to the moment it rose. One small counter does both, and software is too slow for either.

You Will Be Able To

  • Say what a prescaler does, and work out how long one slot and one frame last.
  • Read compare, capture and PWM as three uses of one counter.
  • Explain why hardware, not software, must date an event on a pin.
Lesson
S6.13
Time
24 min
Runs on
Your browser
Check
6 questions

Your code reads the timer as soon as the sensor pulse arrives. The time it logs is always a little late, and never by the same amount. The pulse is on time. What is the log really dating?

Before You Start

You need Registers: software reaches a device through its registers. You need S0.4: one APB write has a setup edge and an access edge.

Timers: The Machine Timer comes first. That timer belongs to the processor. This one is a device on APB, and it can do more.

Five questions this page answers
Question
1What does a prescaler do, and how long does one slot last?
2What does the compare register tell software?
3What does capture save, and why is a read by software not as good?
4What does the duty register set?
5What changes when the prescaler value changes, and what stays the same?

The Idea: One Counter That Goes Round

Picture the hand of a clock that goes round a dial with four marks: 0, 1, 2, 3, and round again. That hand is the whole timer. Everything else is a way to use it.

First you choose how fast the hand moves. The clock of a chip ticks millions of times a second, and a lamp or a motor needs something far slower. So a small counter in front, the prescaler, lets the hand move only once every few clocks.

Then there are three uses. A compare register: hardware tells you when the hand reaches a mark you chose. A capture register: hardware writes down where the hand was when something happened outside. A PWM pin: it is high while the hand is in the first marks of each round, and low for the rest.

All three are done by hardware, on the clock edge. That is the point. Software arrives some unknown number of clocks later, and a timer exists so that this delay does not matter.

New Words

New words on this page
WordMeaning
PrescalerA small counter in front of a timer. The timer steps only when the prescaler has counted a set number of clocks.
SlotOne position of the counter of this timer. It has four: 0, 1, 2 and 3.
FrameOne full round of the counter: four slots.
Compare registerA register that holds a number chosen by software. While the counter equals it, the output named match is 1.
Capture registerA register into which hardware copies the counter at the moment an outside event arrives.
PWMPulse-width modulation: a pin that is high for a chosen part of every frame.
Duty cycleThe part of a frame for which a PWM pin is high, as a fraction or in percent.
The five registers of Timer and PWM that this page uses
OffsetNameWhat software does with it
0x00RUNWrites 1 to bit 0 to start the counter, 0 to stop it.
0x04DUTYWrites the number of slots for which the PWM pin is high: 0 to 4.
0x08CAPTUREDReads the slot number that capture saved.
0x0CDIV_TOPWrites the last count of the prescaler.
0x10COMPAREWrites the slot number that raises match.

Timer and PWM is at base 0x10002000, on APB. Four slots are a teaching size: a real timer counts to 65,535 or more.

One Picture: Prescaler, Counter, Three Uses

One Counter, Three UsesStep through the picture. It starts with a clock and ends with three things a timer does.
  • Clock / reset
  • Control / FSM
  • Bus
  • Memory
  • Peripheral
One Counter, Three UsesStep through the picture. It starts with a clock and ends with three things a timer does. component Prescaler counts clocks: 0 upto DIV_TOP component Slot counter 0, 1, 2, 3 and roundagain component Compare slot equal toCOMPARE? component Capture saves the slot number component PWM slot below DUTY? one step for each fullcountslot numberslot numberslot number
  1. component Prescalercounts clocks: 0 up to DIV_TOP
    • one step for each full count → Slot counter
  2. component Slot counter0, 1, 2, 3 and round again
    • slot number → Compare
    • slot number → Capture
    • slot number → PWM
  3. component Compareslot equal to COMPARE?
  4. component Capturesaves the slot number
  5. component PWMslot below DUTY?
  1. The prescaler

    The clock of the chip is far too fast for a lamp or a motor. The prescaler counts clocks, from 0 up to the value in DIV_TOP, and then starts again.

  2. The slot counter

    Each time the prescaler starts again, the slot counter steps: 0, 1, 2, 3, 0. One slot lasts DIV_TOP + 1 clocks. Four slots are one frame.

  3. Compare: tell me when

    Software writes a slot number into COMPARE. The output named match is 1 while the counter is in that slot.

  4. Capture: when did it happen

    A pulse arrives from outside on the capture input. In that clock the block copies the slot number into CAPTURED. Software reads it later.

  5. PWM: high for part of each frame

    Software writes a number into DUTY. The pin is 1 while the slot number is below it. DUTY = 1 gives one slot of four.

Read the diagram as text
  • Prescaler: counts clocks: 0 up to DIV_TOP
  • Slot counter: 0, 1, 2, 3 and round again
  • Compare: slot equal to COMPARE?
  • Capture: saves the slot number
  • PWM: slot below DUTY?
  • Prescaler → Slot counter: one step for each full count
  • Slot counter → Compare: slot number
  • Slot counter → Capture: slot number
  • Slot counter → PWM: slot number

The Timer and PWM block of ap_soc. The lab below is this block, reached over APB.

The Smallest Example, Worked by Hand

Software writes 1 to DIV_TOP. The prescaler then counts 0, 1, 0, 1, so one slot lasts two clocks and one frame lasts eight. Fill in one frame, clock by clock.

One frame of eight clocks, by hand
Clock01234567
Prescaler count01010101
Slot00112233
PWM pin with DUTY = 111000000
PWM pin with DUTY = 311111100
match with COMPARE = 200001100

With DUTY = 1 the pin is high for two clocks of eight: a duty cycle of one quarter. With DUTY = 3 it is three quarters. The frame is eight clocks long in both rows.

Now capture. A pulse arrives on the capture input in clock 5. The slot in clock 5 is 2, so CAPTURED holds 2. It holds 2 until the next pulse, however late software comes to read it.

The Rules

  1. Rule 1: One slot lasts DIV_TOP + 1 clocks.

    The prescaler counts from 0 up to DIV_TOP, and the slot counter steps when it starts again.

  2. Rule 2: One frame is four slots.

    The slot counter goes 0, 1, 2, 3 and round again while RUN is 1.

  3. Rule 3: match is 1 while the slot equals COMPARE.

    It is a moment chosen in advance. Hardware reports it in the clock in which it comes.

  4. Rule 4: Capture saves the slot of the clock in which the event arrives.

    CAPTURED keeps that number until the next event.

  5. Rule 5: The PWM pin is 1 while the slot is below DUTY.

    DUTY = 0 keeps the pin low. DUTY = 4 keeps it high.

  6. Rule 6: DIV_TOP sets how long a frame lasts. DUTY sets how much of it is high.

    Change one, and the other answer stays the same.

Sources for These Rules

Timers, and pulse-width modulation: Harris and Harris, Digital Design and Computer Architecture, ARM edition, sections 9.3.5 and 9.3.6.2.

The edge on which a register write counts: Arm AMBA APB Protocol Specification, IHI 0024 issue E, section 3.1.

All six rules describe our own Timer and PWM block. Its four slots, its register names and its offsets are our own choices for ap_soc.

Real timers differ in size and in detail. The four ideas, prescaler, compare, capture and PWM, are common to them.

Now Run It

The lab at the end of this page has the Timer and PWM block behind the bridge to APB. Test code, a bus-functional model, stands in for the processor. It writes 1 to DIV_TOP and 2 to COMPARE. Then it starts the timer and tries three values of DUTY.

Printed by the lab on Icarus. In the rows that start with "duty", the first clock of the frame is on the left.
setup addr=10002000 sel=1 enable=0 data=00000001
access addr=10002000 sel=1 enable=1 data=00000001
duty=1 pwm=11000000 compare=00001100
duty=2 pwm=11110000 compare=00001100
duty=3 pwm=11111100 compare=00001100
captured=2 live=0

Rules 1 and 5 at work: the row duty=1 has pwm=11000000. One slot is two clocks, and one slot of four is high. The rows duty=2 and duty=3 add two clocks each.

Rule 3 at work: compare=00001100 in all three rows. The match sits in clocks 4 and 5, which is slot 2, whatever DUTY is.

One Frame at Three Values of DUTY
01234567clkpwm, DUTY 1pwm, DUTY 2pwm, DUTY 3match
Scroll horizontally ↔

The three frames of the lab run, lined up. Each column is one clock. One slot lasts two clocks.

Rule 4 at work: the last row says captured=2 live=0. The pulse came in slot 2. By the time the read was done, the counter had gone on to slot 0.

This lab leaves things out. The capture input is already lined up with the clock: a real pin needs a synchronizer first. The match is not turned into an interrupt here. The Interrupt Path does that with the same block, as source 3.

Why It Is Built This Way

First, rule 6 on the lab. The same run again, with 0 in DIV_TOP in place of 1:

The same lab with DIV_TOP = 0. One slot is one clock, so eight clocks hold two frames.
duty=1 pwm=10001000 compare=00100010
duty=2 pwm=11001100 compare=00100010
duty=3 pwm=11101110 compare=00100010

With DUTY = 1 the pin is high for one clock in four, in place of two in eight. The duty cycle is the same quarter. The frame is half as long, so the pin switches twice as often.

Design choiceThe alternativeWhat the choice buys, and costs
A prescaler in front of the counterOne very wide counterA small counter covers both short and long times. Time is measured in steps of one slot, not one clock.
Capture in hardwareAn interrupt, and a read of the counter in the handlerThe saved number dates the event to the clock. It needs a register and an input for each event.
PWM in hardwareSoftware sets and clears the pinThe edges of the pin stay exact while software is busy. A block and a pin are spent on it.
Duty and frame length in two registersOne register for the high time, one for the low timeBrightness and frequency are set apart. The duty cycle moves only in steps of one slot.

The Trap: Dating an Event by Reading the Timer

Back to the log that is always a little late. The code waits for the sensor pulse, then reads the counter and writes the number down. Look once more at the last row of the lab: captured=2 live=0.

The pulse arrived in slot 2. A read of the live counter, made as soon as the bus allowed, saw slot 0. Software would have logged a time two slots late, and on a busy day three or four. That log dates the read, not the pulse.

The delay is not constant, and that is what makes it a trap. It depends on what the processor was doing: another handler, a slow bus, a cache miss. No fixed correction removes it. The capture register does, because hardware took the number in the clock of the event.

A second trap is rule 6 turned round. Someone wants a dimmer lamp and lowers DIV_TOP. The lamp is as bright as before. It only flickers faster.

At Scale

This page1 counter, 4 slots
A motor-control chipdozens of channels, 16 bits or more each

This section looks ahead. A real timer block is this page with bigger numbers and more copies.

  1. A wider counter

    A 16-bit counter has 65,536 positions. The duty cycle then moves in steps far too small to see or hear.

  2. Channels

    One counter often feeds several compare, capture and PWM channels, so that several pins share one frame.

  3. The match as an interrupt

    A match can set a sticky flag and ask for an interrupt. The Interrupt Path follows exactly that.

  4. Build one

    To write such a counter yourself as hardware, see the programmable timer.

Try It

Run the lab. Check the three rows that start with "duty" against the hand table.

Change pwm_frame(3) to pwm_frame(0), and predict the row before you run it.

Change the value written to TIMER+12 from 1 to 0. One slot now lasts one clock. Count the frames in eight clocks.

Names Printed by the Lab
NameMeaning
setup, accessThe write that starts the timer, at the two clock edges of its APB transfer.
dutyThe value written to DUTY for this frame.
pwmThe PWM pin at eight clocks in a row. The first clock is on the left.
compareThe output named match at the same eight clocks.
capturedThe value that software reads from CAPTURED.
liveThe slot the counter is in at the moment of that read.
RUNIcarus Verilog · in your browser
Edit the code, then run it
Expected: setup addr=10002000 sel=1 enable=0 data=00000001 access addr=10002000 sel=1 enable=1 data=00000001 duty=1 pwm=11000000 compare=00001100 duty=2 pwm=11110000 compare=00001100 duty=3 pwm=11111100 compare=00001100 captured=2 live=0
Read included file: ahb_apb_bridge.sv
`timescale 1ns/1ns
// ahb_apb_bridge.sv: an AHB subordinate that turns each accepted transfer into one APB transfer
// (read-only). The address phase is registered when HSEL, HREADY and a NONSEQ or SEQ transfer are
// all present. During SETUP and unfinished ACCESS the bridge keeps HREADYOUT low. A successful APB
// completion ends the AHB data phase with OKAY and HRDATA = PRDATA. A failed APB completion starts
// the two-cycle ERROR (HREADYOUT low then high, HRESP high in both). HWDATA and HWSTRB are data-phase signals the manager holds
// through the wait states, so PWDATA and PSTRB are driven from them directly; PADDR is the aligned
// word address (IHI 0024E 2.1.1 leaves an unaligned PADDR unpredictable). HPROT maps onto PPROT:
// privileged from HPROT[1], instruction from HPROT[0] = 0, and the access is Secure.
// A write therefore costs one setup and one access cycle: two cycles of data phase with no APB wait.
module ahb_apb_bridge (
  input  logic        hclk,
  input  logic        hresetn,
  input  logic        hsel,
  input  logic [31:0] haddr,
  input  logic [1:0]  htrans,
  input  logic        hwrite,
  input  logic [3:0]  hprot,
  input  logic [31:0] hwdata,
  input  logic [3:0]  hwstrb,
  input  logic        hready,
  output logic        hreadyout,
  output logic        hresp,
  output logic [31:0] hrdata,
  output logic        psel,
  output logic        penable,
  output logic        pwrite,
  output logic [31:0] paddr,
  output logic [31:0] pwdata,
  output logic [3:0]  pstrb,
  output logic [2:0]  pprot,
  input  logic        pready,
  input  logic [31:0] prdata,
  input  logic        pslverr);
  localparam int IDLE = 0, SETUP = 1, ACCESS = 2, ERR1 = 3, ERR2 = 4;
  bit trace = 0;
  int st = IDLE;
  logic        wr = 0;
  logic [31:0] a = 0;
  logic [2:0]  prot = 0;
  wire take = hsel && hready && htrans[1];
  assign psel      = (st == SETUP || st == ACCESS);
  assign penable   = (st == ACCESS);
  assign pwrite    = wr;
  assign paddr     = {a[31:2], 2'b00};     // APB leaves an unaligned PADDR unpredictable: the word, and PSTRB picks the bytes
  assign pwdata    = wr ? hwdata : 32'h0;
  assign pstrb     = wr ? hwstrb : 4'h0;
  assign pprot     = prot;
  assign hreadyout = (st == IDLE || st == ERR2) ? 1'b1 : (st == ACCESS) ? (pready === 1'b1 && pslverr !== 1'b1) : 1'b0;
  assign hresp     = (st == ERR1 || st == ERR2);
  assign hrdata    = (st == ACCESS) ? prdata : 32'h0;
  always @(posedge hclk or negedge hresetn) begin
    if (!hresetn) st <= IDLE;
    else begin
      case (st)
        SETUP:  st <= ACCESS;
        ACCESS: if (pready === 1'b1) begin
                  if (trace) $display("apb e%0d: %0s 0x%03h%0s", ($time - 5) / 10, wr ? "write" : "read", a[11:0], pslverr === 1'b1 ? " PSLVERR" : "");
                  st <= (pslverr === 1'b1) ? ERR1 : IDLE;
                end
        ERR1:   st <= ERR2;
        default: st <= IDLE;
      endcase
      // A new address phase can be taken whenever HREADY is 1: in IDLE, in the last cycle of ERROR,
      // or at the edge an access completes with OKAY.
      if (take && (st == IDLE || st == ERR2 || (st == ACCESS && pready === 1'b1 && pslverr !== 1'b1))) begin
        wr <= hwrite; a <= haddr; prot <= {~hprot[0], 1'b0, hprot[1]}; st <= SETUP;
      end
    end
  end
endmodule
Read included file: time_bus_bfm.svh
// One manager issues aligned words. The P4 bridge and local time slice share HCLK.
// Only the lesson's implemented, always-ready register words are accessed.
logic clk = 0, reset_n = 0;
always #5 clk = ~clk;
logic [31:0] haddr = 0, hwdata = 0;
logic hwrite = 0;
logic [1:0] htrans = 0;
wire bridge_window = haddr[31:16] == 16'h1000;
wire [31:0] local_data, bridge_data, paddr, pwdata, prdata;
wire bridge_ready, hresp, psel, penable, pwrite;
logic bridge_response;
wire hready = !bridge_response || bridge_ready;
logic [31:0] result;
bit trace_access = 0;

always_ff @(posedge clk) begin
  if (!reset_n) bridge_response <= 0;
  else if (hready) bridge_response <= htrans[1] && bridge_window;
end
ahb_apb_bridge bridge (
  .hclk(clk), .hresetn(reset_n), .hsel(bridge_window), .haddr, .htrans, .hwrite,
  .hprot(4'b0011), .hwdata, .hwstrb(4'hf), .hready, .hreadyout(bridge_ready),
  .hresp, .hrdata(bridge_data), .psel, .penable, .pwrite, .paddr, .pwdata,
  .pstrb(), .pprot(), .pready(1'b1), .prdata, .pslverr(1'b0)
);
always @(posedge clk)
  if (trace_access && psel)
    if (penable) $display("access addr=%08h sel=%b enable=%b data=%08h",paddr,psel,penable,pwdata);
    else $display("setup addr=%08h sel=%b enable=%b data=%08h",paddr,psel,penable,pwdata);

task automatic bus_word(input bit wr, input logic [31:0] addr, data,
                        output logic [31:0] sample);
  if (!modeled_word(wr,addr))
    $fatal(1,"This target slice does not model that word operation at %08h",addr);
  @(negedge clk);
  haddr = addr;
  hwrite = wr;
  htrans = 2'b10;
  @(negedge clk);
  haddr = 0;
  htrans = 0;
  hwdata = data;
  do @(posedge clk); while (!hready);
  if (bridge_response && hresp) $fatal(1,"Bus error at %08h",addr);
  sample = bridge_response ? bridge_data : local_data;
  @(negedge clk);
endtask
task automatic apb_word(input bit wr, input logic [31:0] addr, data);
  bus_word(wr,addr,data,result);
endtask
Read included file: timer_demo.svh
`include "time_bus_bfm.svh"
localparam TIMER = 32'h1000_2000, CLINT = 32'h0200_0000;
logic tick = 0, capture = 0;
wire hsel = hready && htrans[1] && haddr[31:16] == CLINT[31:16];
wire [63:0] mtime, mtimecmp;
wire timer_irq, pwm, match;
wire [1:0] phase;
machine_time #(.START(64'hffff_fffe)) ap_clint(
  .clk, .reset_n, .tick, .hsel, .hwrite, .haddr(haddr[15:0]), .hwdata,
  .hrdata(local_data), .mtime, .mtimecmp, .timer_irq
);
capture_pwm peripheral(
  .clk, .reset_n, .psel(psel && paddr[31:12] == TIMER[31:12]),
  .penable, .pwrite, .capture, .offset(paddr[11:0]), .pwdata, .prdata,
  .phase, .pwm, .match
);
function automatic bit modeled_word(input bit wr, input logic [31:0] addr);
  case (addr)
    CLINT+'hbff8, CLINT+'hbffc, CLINT+'h4000, CLINT+'h4004: return 1;
    TIMER, TIMER+4, TIMER+12, TIMER+16: return wr;
    TIMER+8: return !wr;
    default: return 0;
  endcase
endfunction
task automatic machine_word(input bit wr, input logic [15:0] offset,
                            input logic [31:0] data, output logic [31:0] sample);
  bus_word(wr,CLINT + offset,data,sample);
endtask
task automatic advance_time;
  tick = 1;
  @(negedge clk);
  tick = 0;
  $display("mtime=%016h cmp=%016h irq=%b",mtime,mtimecmp,timer_irq);
endtask
task automatic pwm_frame(input integer duty);
  logic [7:0] pins, match_samples;
  apb_word(1,TIMER+4,duty);
  // Align each frame to the transition from slot three into slot zero.
  wait (phase == 3);
  wait (phase == 0);
  for (int i=7; i>=0; i--) begin
    @(negedge clk);
    pins[i] = pwm;
    match_samples[i] = match;
  end
  $display("duty=%0d pwm=%08b compare=%08b",duty,pins,match_samples);
endtask
Read included file: machine_time.sv
// ap_soc timer slice. Word offsets follow the CLINT layout.
// The parent supplies an accepted, aligned word address on HSEL.
module machine_time #(parameter logic [63:0] START = 0) (
  input logic clk, reset_n, tick, hsel, hwrite,
  input logic [15:0] haddr,
  input logic [31:0] hwdata,
  output logic [31:0] hrdata,
  output logic [63:0] mtime, mtimecmp,
  output logic timer_irq
);
  logic selected, writing;
  logic [15:0] offset;
  always_ff @(posedge clk) begin
    if (!reset_n) begin
      selected <= 0;
      writing <= 0;
      offset <= 0;
      mtime <= START;
      mtimecmp <= '1;
    end else begin
      selected <= hsel;
      writing <= hwrite;
      offset <= haddr;
      // A time write replaces the addressed half and suppresses that edge's tick.
      if (selected && writing && offset == 16'hbff8)
        mtime <= {mtime[63:32],hwdata};
      else if (selected && writing && offset == 16'hbffc)
        mtime <= {hwdata,mtime[31:0]};
      else if (tick) mtime <= mtime + 1'b1;
      if (selected && writing) begin
        case (offset)
          16'h4000: mtimecmp[31:0] <= hwdata;
          16'h4004: mtimecmp[63:32] <= hwdata;
          default: ;
        endcase
      end
    end
  end
  always_comb begin
    hrdata = 0;
    if (selected && !writing)
      case (offset)
        16'h4000: hrdata = mtimecmp[31:0];
        16'h4004: hrdata = mtimecmp[63:32];
        16'hbff8: hrdata = mtime[31:0];
        16'hbffc: hrdata = mtime[63:32];
        default: ;
      endcase
  end
  assign timer_irq = mtime >= mtimecmp;
endmodule
Read included file: capture_pwm.sv
// Four-slot peripheral timer. The prescaler top is the last count before a step.
// capture is a synchronous event strobe from the input front end.
module capture_pwm (
  input logic clk, reset_n, psel, penable, pwrite, capture,
  input logic [11:0] offset,
  input logic [31:0] pwdata,
  output logic [31:0] prdata,
  output logic [1:0] phase,
  output logic pwm, match
);
  localparam RUN = 0, DUTY = 4, CAPTURED = 8, DIV_TOP = 12, COMPARE = 16;
  logic running;
  logic [7:0] divider, prescale_top;
  logic [2:0] duty;
  logic [1:0] captured, compare_phase;
  wire write_word = psel && penable && pwrite;

  always_ff @(posedge clk) begin
    if (!reset_n) begin
      running <= 0;
      divider <= 0;
      prescale_top <= 0;
      phase <= 0;
      duty <= 0;
      compare_phase <= 0;
      captured <= 0;
    end else begin
      if (write_word && offset == RUN) running <= pwdata[0];
      if (write_word && offset == DUTY) duty <= pwdata[2:0];
      if (write_word && offset == COMPARE) compare_phase <= pwdata[1:0];

      if (write_word && offset == DIV_TOP) begin
        prescale_top <= pwdata[7:0];
        divider <= 0;
      end else if (running) begin
        if (divider == prescale_top) begin
          divider <= 0;
          phase <= phase + 1'b1;
        end else divider <= divider + 1'b1;
      end
      if (capture) captured <= phase;
    end
  end
  assign prdata = offset == CAPTURED ? {30'b0,captured} : 0;
  assign pwm = running && phase < duty;
  assign match = running && phase == compare_phase;
endmodule

Check Yourself

Predict the outputIn this run DIV_TOP is 1, COMPARE is 2 and DUTY is 4. What does the lab print?
`timescale 1ns/1ns
module tb;
  `include "timer_demo.svh"

  initial begin
    repeat (2) @(negedge clk);
    reset_n = 1;
    apb_word(1,TIMER+12,1);
    apb_word(1,TIMER+16,2);
    apb_word(1,TIMER,1);
    pwm_frame(4);
    $finish;
  end
endmodule
Read included file: ahb_apb_bridge.sv
`timescale 1ns/1ns
// ahb_apb_bridge.sv: an AHB subordinate that turns each accepted transfer into one APB transfer
// (read-only). The address phase is registered when HSEL, HREADY and a NONSEQ or SEQ transfer are
// all present. During SETUP and unfinished ACCESS the bridge keeps HREADYOUT low. A successful APB
// completion ends the AHB data phase with OKAY and HRDATA = PRDATA. A failed APB completion starts
// the two-cycle ERROR (HREADYOUT low then high, HRESP high in both). HWDATA and HWSTRB are data-phase signals the manager holds
// through the wait states, so PWDATA and PSTRB are driven from them directly; PADDR is the aligned
// word address (IHI 0024E 2.1.1 leaves an unaligned PADDR unpredictable). HPROT maps onto PPROT:
// privileged from HPROT[1], instruction from HPROT[0] = 0, and the access is Secure.
// A write therefore costs one setup and one access cycle: two cycles of data phase with no APB wait.
module ahb_apb_bridge (
  input  logic        hclk,
  input  logic        hresetn,
  input  logic        hsel,
  input  logic [31:0] haddr,
  input  logic [1:0]  htrans,
  input  logic        hwrite,
  input  logic [3:0]  hprot,
  input  logic [31:0] hwdata,
  input  logic [3:0]  hwstrb,
  input  logic        hready,
  output logic        hreadyout,
  output logic        hresp,
  output logic [31:0] hrdata,
  output logic        psel,
  output logic        penable,
  output logic        pwrite,
  output logic [31:0] paddr,
  output logic [31:0] pwdata,
  output logic [3:0]  pstrb,
  output logic [2:0]  pprot,
  input  logic        pready,
  input  logic [31:0] prdata,
  input  logic        pslverr);
  localparam int IDLE = 0, SETUP = 1, ACCESS = 2, ERR1 = 3, ERR2 = 4;
  bit trace = 0;
  int st = IDLE;
  logic        wr = 0;
  logic [31:0] a = 0;
  logic [2:0]  prot = 0;
  wire take = hsel && hready && htrans[1];
  assign psel      = (st == SETUP || st == ACCESS);
  assign penable   = (st == ACCESS);
  assign pwrite    = wr;
  assign paddr     = {a[31:2], 2'b00};     // APB leaves an unaligned PADDR unpredictable: the word, and PSTRB picks the bytes
  assign pwdata    = wr ? hwdata : 32'h0;
  assign pstrb     = wr ? hwstrb : 4'h0;
  assign pprot     = prot;
  assign hreadyout = (st == IDLE || st == ERR2) ? 1'b1 : (st == ACCESS) ? (pready === 1'b1 && pslverr !== 1'b1) : 1'b0;
  assign hresp     = (st == ERR1 || st == ERR2);
  assign hrdata    = (st == ACCESS) ? prdata : 32'h0;
  always @(posedge hclk or negedge hresetn) begin
    if (!hresetn) st <= IDLE;
    else begin
      case (st)
        SETUP:  st <= ACCESS;
        ACCESS: if (pready === 1'b1) begin
                  if (trace) $display("apb e%0d: %0s 0x%03h%0s", ($time - 5) / 10, wr ? "write" : "read", a[11:0], pslverr === 1'b1 ? " PSLVERR" : "");
                  st <= (pslverr === 1'b1) ? ERR1 : IDLE;
                end
        ERR1:   st <= ERR2;
        default: st <= IDLE;
      endcase
      // A new address phase can be taken whenever HREADY is 1: in IDLE, in the last cycle of ERROR,
      // or at the edge an access completes with OKAY.
      if (take && (st == IDLE || st == ERR2 || (st == ACCESS && pready === 1'b1 && pslverr !== 1'b1))) begin
        wr <= hwrite; a <= haddr; prot <= {~hprot[0], 1'b0, hprot[1]}; st <= SETUP;
      end
    end
  end
endmodule
Read included file: time_bus_bfm.svh
// One manager issues aligned words. The P4 bridge and local time slice share HCLK.
// Only the lesson's implemented, always-ready register words are accessed.
logic clk = 0, reset_n = 0;
always #5 clk = ~clk;
logic [31:0] haddr = 0, hwdata = 0;
logic hwrite = 0;
logic [1:0] htrans = 0;
wire bridge_window = haddr[31:16] == 16'h1000;
wire [31:0] local_data, bridge_data, paddr, pwdata, prdata;
wire bridge_ready, hresp, psel, penable, pwrite;
logic bridge_response;
wire hready = !bridge_response || bridge_ready;
logic [31:0] result;
bit trace_access = 0;

always_ff @(posedge clk) begin
  if (!reset_n) bridge_response <= 0;
  else if (hready) bridge_response <= htrans[1] && bridge_window;
end
ahb_apb_bridge bridge (
  .hclk(clk), .hresetn(reset_n), .hsel(bridge_window), .haddr, .htrans, .hwrite,
  .hprot(4'b0011), .hwdata, .hwstrb(4'hf), .hready, .hreadyout(bridge_ready),
  .hresp, .hrdata(bridge_data), .psel, .penable, .pwrite, .paddr, .pwdata,
  .pstrb(), .pprot(), .pready(1'b1), .prdata, .pslverr(1'b0)
);
always @(posedge clk)
  if (trace_access && psel)
    if (penable) $display("access addr=%08h sel=%b enable=%b data=%08h",paddr,psel,penable,pwdata);
    else $display("setup addr=%08h sel=%b enable=%b data=%08h",paddr,psel,penable,pwdata);

task automatic bus_word(input bit wr, input logic [31:0] addr, data,
                        output logic [31:0] sample);
  if (!modeled_word(wr,addr))
    $fatal(1,"This target slice does not model that word operation at %08h",addr);
  @(negedge clk);
  haddr = addr;
  hwrite = wr;
  htrans = 2'b10;
  @(negedge clk);
  haddr = 0;
  htrans = 0;
  hwdata = data;
  do @(posedge clk); while (!hready);
  if (bridge_response && hresp) $fatal(1,"Bus error at %08h",addr);
  sample = bridge_response ? bridge_data : local_data;
  @(negedge clk);
endtask
task automatic apb_word(input bit wr, input logic [31:0] addr, data);
  bus_word(wr,addr,data,result);
endtask
Read included file: timer_demo.svh
`include "time_bus_bfm.svh"
localparam TIMER = 32'h1000_2000, CLINT = 32'h0200_0000;
logic tick = 0, capture = 0;
wire hsel = hready && htrans[1] && haddr[31:16] == CLINT[31:16];
wire [63:0] mtime, mtimecmp;
wire timer_irq, pwm, match;
wire [1:0] phase;
machine_time #(.START(64'hffff_fffe)) ap_clint(
  .clk, .reset_n, .tick, .hsel, .hwrite, .haddr(haddr[15:0]), .hwdata,
  .hrdata(local_data), .mtime, .mtimecmp, .timer_irq
);
capture_pwm peripheral(
  .clk, .reset_n, .psel(psel && paddr[31:12] == TIMER[31:12]),
  .penable, .pwrite, .capture, .offset(paddr[11:0]), .pwdata, .prdata,
  .phase, .pwm, .match
);
function automatic bit modeled_word(input bit wr, input logic [31:0] addr);
  case (addr)
    CLINT+'hbff8, CLINT+'hbffc, CLINT+'h4000, CLINT+'h4004: return 1;
    TIMER, TIMER+4, TIMER+12, TIMER+16: return wr;
    TIMER+8: return !wr;
    default: return 0;
  endcase
endfunction
task automatic machine_word(input bit wr, input logic [15:0] offset,
                            input logic [31:0] data, output logic [31:0] sample);
  bus_word(wr,CLINT + offset,data,sample);
endtask
task automatic advance_time;
  tick = 1;
  @(negedge clk);
  tick = 0;
  $display("mtime=%016h cmp=%016h irq=%b",mtime,mtimecmp,timer_irq);
endtask
task automatic pwm_frame(input integer duty);
  logic [7:0] pins, match_samples;
  apb_word(1,TIMER+4,duty);
  // Align each frame to the transition from slot three into slot zero.
  wait (phase == 3);
  wait (phase == 0);
  for (int i=7; i>=0; i--) begin
    @(negedge clk);
    pins[i] = pwm;
    match_samples[i] = match;
  end
  $display("duty=%0d pwm=%08b compare=%08b",duty,pins,match_samples);
endtask
Read included file: machine_time.sv
// ap_soc timer slice. Word offsets follow the CLINT layout.
// The parent supplies an accepted, aligned word address on HSEL.
module machine_time #(parameter logic [63:0] START = 0) (
  input logic clk, reset_n, tick, hsel, hwrite,
  input logic [15:0] haddr,
  input logic [31:0] hwdata,
  output logic [31:0] hrdata,
  output logic [63:0] mtime, mtimecmp,
  output logic timer_irq
);
  logic selected, writing;
  logic [15:0] offset;
  always_ff @(posedge clk) begin
    if (!reset_n) begin
      selected <= 0;
      writing <= 0;
      offset <= 0;
      mtime <= START;
      mtimecmp <= '1;
    end else begin
      selected <= hsel;
      writing <= hwrite;
      offset <= haddr;
      // A time write replaces the addressed half and suppresses that edge's tick.
      if (selected && writing && offset == 16'hbff8)
        mtime <= {mtime[63:32],hwdata};
      else if (selected && writing && offset == 16'hbffc)
        mtime <= {hwdata,mtime[31:0]};
      else if (tick) mtime <= mtime + 1'b1;
      if (selected && writing) begin
        case (offset)
          16'h4000: mtimecmp[31:0] <= hwdata;
          16'h4004: mtimecmp[63:32] <= hwdata;
          default: ;
        endcase
      end
    end
  end
  always_comb begin
    hrdata = 0;
    if (selected && !writing)
      case (offset)
        16'h4000: hrdata = mtimecmp[31:0];
        16'h4004: hrdata = mtimecmp[63:32];
        16'hbff8: hrdata = mtime[31:0];
        16'hbffc: hrdata = mtime[63:32];
        default: ;
      endcase
  end
  assign timer_irq = mtime >= mtimecmp;
endmodule
Read included file: capture_pwm.sv
// Four-slot peripheral timer. The prescaler top is the last count before a step.
// capture is a synchronous event strobe from the input front end.
module capture_pwm (
  input logic clk, reset_n, psel, penable, pwrite, capture,
  input logic [11:0] offset,
  input logic [31:0] pwdata,
  output logic [31:0] prdata,
  output logic [1:0] phase,
  output logic pwm, match
);
  localparam RUN = 0, DUTY = 4, CAPTURED = 8, DIV_TOP = 12, COMPARE = 16;
  logic running;
  logic [7:0] divider, prescale_top;
  logic [2:0] duty;
  logic [1:0] captured, compare_phase;
  wire write_word = psel && penable && pwrite;

  always_ff @(posedge clk) begin
    if (!reset_n) begin
      running <= 0;
      divider <= 0;
      prescale_top <= 0;
      phase <= 0;
      duty <= 0;
      compare_phase <= 0;
      captured <= 0;
    end else begin
      if (write_word && offset == RUN) running <= pwdata[0];
      if (write_word && offset == DUTY) duty <= pwdata[2:0];
      if (write_word && offset == COMPARE) compare_phase <= pwdata[1:0];

      if (write_word && offset == DIV_TOP) begin
        prescale_top <= pwdata[7:0];
        divider <= 0;
      end else if (running) begin
        if (divider == prescale_top) begin
          divider <= 0;
          phase <= phase + 1'b1;
        end else divider <= divider + 1'b1;
      end
      if (capture) captured <= phase;
    end
  end
  assign prdata = offset == CAPTURED ? {30'b0,captured} : 0;
  assign pwm = running && phase < duty;
  assign match = running && phase == compare_phase;
endmodule
ConceptDIV_TOP holds 1. How long does one slot last?
ConceptWhat does the compare register tell software?
ConceptWhy is capture better than a read of the counter by software?
ConceptDUTY holds 3. For how much of each frame is the PWM pin high?
ConceptDIV_TOP is changed from 1 to 0, and DUTY stays 1. What happens to the PWM pin?

Common Mistakes

Wrong Date an event on a pin by reading the counter in software.

The read comes an unknown number of clocks after the event.

Fix Let capture save the counter, and read CAPTURED.

Wrong Change the prescaler to change the brightness of a lamp.

DIV_TOP stretches the high part and the low part alike.

Fix Change DUTY for the duty cycle, and DIV_TOP for the length of a frame.

Wrong Take the prescaler value as the number of clocks in a slot.

The prescaler counts from 0, so DIV_TOP = 1 means two clocks.

Fix One slot lasts DIV_TOP + 1 clocks.

Remember

  • A prescaler slows a counter: one slot lasts DIV_TOP + 1 clocks, and four slots are one frame.
  • Compare reports a moment chosen in advance. Capture saves the moment of an outside event.
  • PWM holds a pin high while the slot is below DUTY. DIV_TOP sets the frame, DUTY the duty cycle.
  • Hardware does all three on the clock edge, because software always arrives late.

Practice

Report a problem with this page