Pulse Measurement (PASM2)
JonnyMac
Posts: 9,507
I still haven't been able to wrap my head around measuring a low-going pulse with P2 smart pins, so I thought I'd give brute-force another try. I have working code now, but it's a bit much -- this is simpler. The goal is to measure a low-going pulse. The code will wait tous (timeout microseconds) for the pulse to arrive, which can be up to tous microseconds wide. For the moment I am testing with inline PASM2, but this will be folded into a PASM cog/cpu. I've been feeling a bit janky for a couple days (sleep cycle is off), so if I've done something really silly, please go easy. 
FWIW, this code does work. I connected an IR sensor and measured the leader pulse from a Sony remote. The result comes back near 2400 microseconds which is what it is supposed to be.
FWIW, this code does work. I connected an IR sensor and measured the leader pulse from a Sony remote. The result comes back near 2400 microseconds which is what it is supposed to be.
pub pulse0_in(pin, tous) : result | check, t1, t2
org
testp pin wc ' scan input
if_c mov check, #1
if_nc mov check, #0
' wait for up to timeout microseconds (tous) for high-to-low transition
.wait getct t1 ' sync with sys counter
mov t2, #0 ' reset timeout
.loop1 addct1 t1, #US_001 ' wait 1us
waitct1
testp pin wc ' scan input
rcl check, #1 ' move into lsb of check
and check, #$0F ' isolate 5 scans
cmp check, #%1110 wz ' clean falling edge?
if_e jmp #.loop0 ' yes, measure pulse
incmod t2, tous wc ' increment with roll-over
if_nc jmp #.loop1
jmp #.done ' timeout, return 0
' measure low for up to tous
.loop0 addct1 t1, #US_001 ' wait 1us
waitct1
incmod result, tous wc ' update pulse width
if_c jmp #.done ' - abort on time out
testp pin wc ' rescan pin
if_nc jmp #.loop0 ' continue if still low
.done
end

Comments
I tested it by also using %TT = %01 to enable the output. Then I could use OUT to toggle the pin, with the smartpin measuring it. This is my test code, minus the debug wrapper. The wrapper has a bunch of constants for things like smartpin modes, as well as the comport print routines.