Skip to content

Instantly share code, notes, and snippets.

@jck
Created July 22, 2015 09:48
Show Gist options
  • Save jck/ab2a6a033393c8854ec4 to your computer and use it in GitHub Desktop.
Save jck/ab2a6a033393c8854ec4 to your computer and use it in GitHub Desktop.
MyHDL nonlocal
from myhdl import *
ACTIVE = 0
DirType = enum('RIGHT', 'LEFT')
def jc2(goLeft, goRight, stop, clk, q):
""" A bi-directional 4-bit Johnson counter with stop control.
I/O pins:
--------
clk : input free-running slow clock
goLeft : input signal to shift left (active-low switch)
goRight : input signal to shift right (active-low switch)
stop : input signal to stop counting (active-low switch)
q : 4-bit counter output (active-low LEDs; q[0] is right-most)
"""
dir = DirType.LEFT
run = False
@always(clk.posedge)
def logic():
nonlocal dir, run
# direction
if goRight == ACTIVE:
dir = DirType.RIGHT
run = True
elif goLeft == ACTIVE:
dir = DirType.LEFT
run = True
# stop
if stop == ACTIVE:
run = False
# counter action
if run:
if dir == DirType.LEFT:
q.next[4:1] = q[3:]
q.next[0] = not q[3]
else:
q.next[3:] = q[4:1]
q.next[3] = not q[0]
return logic
goLeft goRight stop clk q
-------------------------
1 1 1 C 0000
1 1 1 C 0000
0 1 1 C 0001
1 1 1 C 0011
1 1 1 C 0111
1 1 1 C 1111
1 1 1 C 1110
1 1 1 C 1100
1 1 1 C 1000
1 1 1 C 0000
1 1 1 C 0001
1 1 1 C 0011
1 1 0 C 0011
1 1 1 C 0011
1 1 1 C 0011
1 0 1 C 0001
1 1 1 C 0000
1 1 1 C 1000
1 1 1 C 1100
1 1 1 C 1110
1 1 1 C 1111
1 1 1 C 0111
1 1 1 C 0011
1 1 1 C 0001
1 1 1 C 0000
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment