Skip to content
systemcoding.dev
Hardware

Write a state machine with the with m.FSM() block in Amaranth

Build an Amaranth 0.5 state machine with with m.FSM(), named m.State blocks and m.next, where the first State declared is the reset state.

1 min read
Summarize in AI

Amaranth has a state machine construct, so you do not write a state register and a case by hand. You open an FSM block, add a State per name and set m.next to change state.

ctl.pypython
from amaranth import *

class Ctl(Elaboratable):
    def __init__(self):
        self.start = Signal()
        self.done  = Signal()
        self.busy  = Signal()

    def elaborate(self, platform):
        m = Module()
        with m.FSM():
            with m.State("IDLE"):
                with m.If(self.start):
                    m.next = "RUN"
            with m.State("RUN"):
                m.d.comb += self.busy.eq(1)
                with m.If(self.done):
                    m.next = "IDLE"
        return m

The first State you declare is the reset state, so IDLE here, and there is no separate way to name it. Assigning m.next takes effect on the next clock edge, and where no m.next is reached, the machine stays in the current state.

Names are strings, which Amaranth maps to encoded values and keeps for waveform output, so a trace shows RUN and not 1. Signals assigned with m.d.comb inside a state, like busy above, hold their default (zero) in every other state, which gives you a Moore-style output without writing the default yourself.

You can read the current state with m.ongoing("RUN") in other logic, and it returns a signal that is high while the machine is in that state.

Share

More snippets

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.