Skip to content

Instantly share code, notes, and snippets.

@jepler
Created January 7, 2023 19:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jepler/d3218e45219920852592b5b954ec566f to your computer and use it in GitHub Desktop.
Save jepler/d3218e45219920852592b5b954ec566f to your computer and use it in GitHub Desktop.
import array
import digitalio
import board
import adafruit_pioasm
import rp2pio
program = adafruit_pioasm.Program(""".program clocked_input_chip_select
; Sample bits using an external clock, and push groups of bits into the RX FIFO.
; - IN pin 0 is the data pin
; - IN pin 1 is the dc pin
; - IN pin 2 is the clock pin
; - JMP pin is the chip select
; - Autopush is enabled, threshold 8
;
; This program waits for chip select to be asserted (low) before it begins
; clocking in data. Whilst chip select is low, data is clocked continuously. If
; chip select is deasserted part way through a data byte, the partial data is
; discarded. This makes use of the fact a mov to isr clears the input shift
; counter.
flush:
mov isr, null ; Clear ISR and input shift counter
jmp check_chip_select ; Poll chip select again
.wrap_target
do_bit:
wait 0 pin 2 ; Detect rising edge and sample input data
wait 1 pin 2 ; (autopush takes care of moving each complete
in pins, 2 ; data word to the FIFO)
check_chip_select:
jmp pin, flush ; Bail out if we see chip select high
.wrap
""", build_debuginfo=True)
print(program.assembled)
program.print_c_program('bob')
sm = rp2pio.StateMachine(
program.assembled,
first_in_pin=board.GP2,
in_pin_count=3,
pull_in_pin_up=0x7,
jmp_pin=board.GP5,
jmp_pin_pull=digitalio.Pull.UP,
in_shift_right=False,
auto_push=True,
push_threshold=16,
frequency=120_000_000,
**program.pio_kwargs,
)
lookup = [0] * 256
for i in range(256):
bits = [(i >> j) & 1 for j in range(8)]
k = (
(bits[0] << 0) |
(bits[1] << 2) |
(bits[2] << 4) |
(bits[3] << 6) |
(bits[4] << 1) |
(bits[5] << 3) |
(bits[6] << 5) |
(bits[7] << 7))
lookup[k] = i
a = array.array('H', [0])
i = 0
while True:
sm.readinto(a)
i += 1
v = a[0]
command = not v & 2
aa = (v & 0x55) | ((v >> 7) & 0xaa)
vv = lookup[aa]
if command:
print(end=f"\nCMD {vv:02x}\n ")
i = 0
else:
i += 1
print(f"{vv:02x}", end="\n" if i == 16 else " ")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment