RTL Design #54 · 2026-11-16 · FSMs · Medium · about 25 min

Vending machine controller

Build the controller of a small vending machine. One item costs 15 cents. The machine accepts nickels (5 cents) and dimes (10 cents), one coin per clock.

Write vending in vending.sv. At every rising edge (when rst_n is 1), in this order of priority:

  1. cancel = 1: whatever credit is held is returned and the credit becomes 0. refund shows, for the next cycle, the number of nickels returned (0, 1 or 2). A coin on the same clock as cancel is ignored: it is not added and not returned.
  2. Otherwise the coin is added to the credit: 2'b01 is a nickel, 2'b10 is a dime, 2'b00 and 2'b11 are no coin.
  3. If the credit is now 15 or more, the item is sold: dispense is 1 for the next cycle, and change is also 1 for that cycle if the credit reached 20 (a 5-cent coin back). The credit becomes 0.

dispense, change and refund are registered outputs. Each is a one-cycle pulse, and 0 on every cycle that follows neither a sale nor a cancel. Reset is synchronous, active low: it clears the credit and all three outputs.

Worked example (credit before the edge, coin and cancel sampled at the edge, outputs after it):

edge credit coin cancel dispense change refund
1 0 nickel 0 0 0 0
2 5 dime 0 1 0 0
3 0 dime 0 0 0 0
4 10 dime 0 1 1 0
5 0 dime 0 0 0 0
6 10 none 1 0 0 2

tb in testbench.sv replays this sequence. Submit runs hidden tests on the rest.

Write and run your answer in the browser. The hidden tests check it, and it’s free.