Priority encoder
When several requests are active, apply a specified priority order and return the winner’s index. Index 0 can occur both with no request and when request 0 wins, so use valid to indicate when the index can be used.
Four sensors can request service at the same time. The collector serves one at a time, so a priority encoder chooses a winner and returns its index on idx[1:0]. With req[3:0]=0101, channels two and zero are both waiting.
The priority can change while the requests stay the same
With high_first=1, scan from channel three down. Channel three is clear and channel two is set, so idx=2. Change high_first to zero and scan upward from channel zero. The same request bits now produce idx=0. The encoder keeps no record of past winners. A rotating arbiter needs state to remember earlier service.
With req=0001, channel zero wins and the outputs are valid=1, idx=0. With req=0000, the index is again zero but valid=0. The receiver checks valid before treating idx as a selected channel.
Synthesizable SystemVerilog
module priority_encoder4 (
input logic [3:0] req,
input logic high_first,
output logic valid,
output logic [1:0] idx
);
always_comb begin
valid = |req;
idx = 2'd0;
if (high_first) begin
if (req[3]) idx = 2'd3;
else if (req[2]) idx = 2'd2;
else if (req[1]) idx = 2'd1;
end else begin
if (req[0]) idx = 2'd0;
else if (req[1]) idx = 2'd1;
else if (req[2]) idx = 2'd2;
else if (req[3]) idx = 2'd3;
end
end
endmodule
Check the results against the waveform
The request mask is binary. The index is decimal.
| Change at | req | high_first | valid | idx |
|---|---|---|---|---|
| 0 ns | 0101 | 1 | 1 | 2 |
| 10 ns | 0101 | 0 | 1 | 0 |
| 20 ns | 0001 | 1 | 1 | 0 |
| 30 ns | 0000 | 1 | 0 | 0 |
| 40 ns | 1010 | 1 | 1 | 3 |
A test with only one request always picks the same channel. Use 0101 to check which of two simultaneous requests has priority.
Download the runnable SystemVerilog lab. Icarus checks the 5 rows above and 32 binary input combinations. It reads each directed result 1 ns after changing the inputs. The wait sets an observation time in the testbench. The waveform is functional evidence. Physical delay needs a timing model.
Interactive lab
Keep req at 0101 and switch the priority direction. Then compare no request with a win for channel zero.
- Request valid
- Winning index idx
Show the last eight observations
Teaching film
Run the RTL yourself
Extract the lab and follow the commands in its README. Compare the simulated outputs and waveform with your predictions from the interactive lab.
Download Priority encoder RTL (.zip)