; PULSIN.ASM
;
; Illustrates an implementation of the Basic Stamp's PULSIN command.
; 
; Subroutine PULSE_0 measures the amount of time between the falling
; edge of a pulse on RA.2 to the next rising edge.  The amount of time
; is returned to the calling program in TICK_H and TICK_L where the count
; is the number 5 usecs.  Thus, times of up to 327 msecs (65534 * 5 usecs)
; may be measured.
;
; A value of FFFFH is returned if a falling edge was not found within
; 327 msecs or the zero time was greater than 327 msecs.
;
; On entry into into the PULSIN_0 routine, the program loops to ZERO
; until the input goes high.  It then loops in ONE until the input goes
; to zero.  At EDGE_0, the program then loops until the input again goes
; positive.
;
; The timing from EDGE_0 to EDGE_1 is accomplished by counting the
; number of passes through the loop, each pass being 5 usecs.  
; 
; However, after 256 passes, there is some additional time associated 
; with incrementing the high byte (TICK_H).
;
; This program simply calls PULSIN_0.  It does nothing with TICK_H and
; TICK_L. 
;
; Note that a very similar routine could be developed for determining 
; the amount of time a pulse is at a logic one.  This gives the developer
; the capability of then measuring the period.
;
; copyright, H. Paul Roach, Baltimore, MD, Feb, '98                


	LIST p=16f84	
#include <c:\mplab\p16f84.inc>	
	__CONFIG 11h

	CONSTANT VARS=0CH

TICK_L	EQU VARS+0	; amount of time in 5 usecs counts	
TICK_H	EQU VARS+1

	ORG 000H

	BSF STATUS, RP0		
	BSF TRISA, 2		; make RA2 (terminal 1) an input		
	BCF STATUS, RP0		

MAIN:
	CALL	PULSIN_0
	GOTO	MAIN

PULSIN_0:
ZERO:
	CLRF	TICK_H
	CLRF	TICK_L

ZERO_1:				; if at logic zero loop
	BTFSC	PORTA, 2
	GOTO	ONE
	INCFSZ	TICK_L, F
	GOTO	ZERO_1
	INCFSZ	TICK_H, F
	GOTO	ZERO_1
	GOTO	PULSIN_0_OVR_FLOW	

ONE:				; at logic one, wait for transition
	CLRF	TICK_H
	CLRF	TICK_L

ONE_1:
	BTFSS	PORTA, 2
	GOTO	EDGE_0
	INCFSZ	TICK_L, F
	GOTO	ONE_1
	INCFSZ	TICK_H, F
	GOTO	ONE_1
	GOTO	PULSIN_0_OVR_FLOW
	
EDGE_0:				; 1 to 0 transition occurred
	CLRF	TICK_H
	CLRF	TICK_L

EDGE_0_1:
	BTFSC	PORTA, 2	; 2 ~ this is the 5 usec time loop
	GOTO	EDGE_1		; 
	INCFSZ	TICK_L, F	; 1~
	GOTO	EDGE_0_1	; 2 ~
	INCFSZ	TICK_H, F
	GOTO	EDGE_0_1
	GOTO	PULSIN_0_OVR_FLOW

EDGE_1:
	RETURN

PULSIN_0_OVR_FLOW:		; fill TICK_H and TICK_L with FFFFH

	MOVLW	0FFH
	MOVWF	TICK_H
	MOVWF	TICK_L
	RETURN

	END