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.
| Question | |
|---|---|
| 1 | What does a prescaler do, and how long does one slot last? |
| 2 | What does the compare register tell software? |
| 3 | What does capture save, and why is a read by software not as good? |
| 4 | What does the duty register set? |
| 5 | What 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
| Word | Meaning |
|---|---|
| Prescaler | A small counter in front of a timer. The timer steps only when the prescaler has counted a set number of clocks. |
| Slot | One position of the counter of this timer. It has four: 0, 1, 2 and 3. |
| Frame | One full round of the counter: four slots. |
| Compare register | A register that holds a number chosen by software. While the counter equals it, the output named match is 1. |
| Capture register | A register into which hardware copies the counter at the moment an outside event arrives. |
| PWM | Pulse-width modulation: a pin that is high for a chosen part of every frame. |
| Duty cycle | The part of a frame for which a PWM pin is high, as a fraction or in percent. |
| Offset | Name | What software does with it |
|---|---|---|
| 0x00 | RUN | Writes 1 to bit 0 to start the counter, 0 to stop it. |
| 0x04 | DUTY | Writes the number of slots for which the PWM pin is high: 0 to 4. |
| 0x08 | CAPTURED | Reads the slot number that capture saved. |
| 0x0C | DIV_TOP | Writes the last count of the prescaler. |
| 0x10 | COMPARE | Writes 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
- Clock / reset
- Control / FSM
- Bus
- Memory
- Peripheral
- 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.
- 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.
- Compare: tell me when
Software writes a slot number into COMPARE. The output named match is 1 while the counter is in that slot.
- 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.
- 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.
| Clock | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|---|
| Prescaler count | 0 | 1 | 0 | 1 | 0 | 1 | 0 | 1 |
| Slot | 0 | 0 | 1 | 1 | 2 | 2 | 3 | 3 |
| PWM pin with DUTY = 1 | 1 | 1 | 0 | 0 | 0 | 0 | 0 | 0 |
| PWM pin with DUTY = 3 | 1 | 1 | 1 | 1 | 1 | 1 | 0 | 0 |
| match with COMPARE = 2 | 0 | 0 | 0 | 0 | 1 | 1 | 0 | 0 |
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
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.
Rule 2: One frame is four slots.
The slot counter goes 0, 1, 2, 3 and round again while RUN is 1.
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.
Rule 4: Capture saves the slot of the clock in which the event arrives.
CAPTURED keeps that number until the next event.
Rule 5: The PWM pin is 1 while the slot is below DUTY.
DUTY = 0 keeps the pin low. DUTY = 4 keeps it high.
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.
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=0Rules 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.
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:
duty=1 pwm=10001000 compare=00100010
duty=2 pwm=11001100 compare=00100010
duty=3 pwm=11101110 compare=00100010With 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 choice | The alternative | What the choice buys, and costs |
|---|---|---|
| A prescaler in front of the counter | One very wide counter | A small counter covers both short and long times. Time is measured in steps of one slot, not one clock. |
| Capture in hardware | An interrupt, and a read of the counter in the handler | The saved number dates the event to the clock. It needs a register and an input for each event. |
| PWM in hardware | Software sets and clears the pin | The 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 registers | One register for the high time, one for the low time | Brightness 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 section looks ahead. A real timer block is this page with bigger numbers and more copies.
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.
Channels
One counter often feeds several compare, capture and PWM channels, so that several pins share one frame.
The match as an interrupt
A match can set a sticky flag and ask for an interrupt. The Interrupt Path follows exactly that.
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
| Name | Meaning |
|---|---|
| setup, access | The write that starts the timer, at the two clock edges of its APB transfer. |
| duty | The value written to DUTY for this frame. |
| pwm | The PWM pin at eight clocks in a row. The first clock is on the left. |
| compare | The output named match at the same eight clocks. |
| captured | The value that software reads from CAPTURED. |
| live | The slot the counter is in at the moment of that read. |
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=0Read 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
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.