Hi!
BigEd wrote:
Here's a mini-challenge for you. I have a real application in mind too, so it's not artificial.
You have an 8 bit input port at some absolute address, and the challenge is to write a subroutine which waits for every pin to toggle (change state) at least twice, and then returns. (It should of course return as soon as every pin has toggled twice, regardless of the starting state of the inputs and the order in which they toggle. They might all change together, or one by one.)
This kind of problem (having to perform logic for all bits in a byte/word) can be solved by a technique called "vertical counters", see
https://everything2.com/title/vertical+counter for a little explanation.
In your case, you can define a state machine with three states, representing the number of transitions seen, state A, B and C. You got from A to B of from B to C if you detect a transition, and do nothing in all other cases. If you encode with two bits, "x" and "y", using A = "00", B = "01" and "C = "11", your logic table is:
Code:
In xy x'y'
-----------
0 00 00
0 01 01
0 10 --
0 11 11
1 00 01
1 01 11
1 10 --
1 11 11
This simplifies to the two equations: x' = x+I*y and y' = y + I.
Now, the (untested) code:
Code:
' Three ZP locations for our variables:
OLD_IN = $10
S_X = $11
S_Y = $12
wait:
' Init old input var
lda INPUTS
sta OLD_IN
lda #0
ldy #0
loop:
' Store state
sta S_X
sty S_Y
' Check toggled bits updating old value
lda OLD_IN
tax
eor INPUTS
stx OLD_IN
' Store for later
tax
' Now, get new Y
ora S_Y
tay
' And the get new X
txa
and S_Y
ora S_X
' Compare X with 255 (al bits set)
cmp #255
bne loop
' Ok!
rts
Have Fun!