;**************************************************************************
;Fibonnaci + Storage
;In a Fibonacci series each number is the sum of the two 
;previous ones, e.g. 0,1,1,2,3,5,8,13,21....
;This program calculates Fibonacci numbers within an 8-bit range,
;first going up and then down. Series is stored using Indirect Addressing 
;in a block of data memory starting at 20H.
;Program intended for simulation only, hence no input/output.
;The program demonstrates addition, subtraction, compare. 
;TJW 10.10.05								Tested by simulation 12.10.05
;**************************************************************************

	list p=16F84A
	include P16f84A.inc
;no i/o ports used
status  equ 03
c		equ 0
z		equ 2
;these memory locations hold the most recent numbers in the Fibonacci series
fib0	equ  10	;lowest number (oldest when going up; newest when reversing down)
fib1    equ  11 ;middle number
fib2    equ  12 ;highest number
fibtemp equ  13 ;temporary location for newest number
counter equ  14 ;indicates which value we have reached, opening value is 3 

	org 00
;preload initial values
		movlw 0
		movwf fib0
		movwf	20	;save at start of list
		movlw 1

		movwf fib1
		movwf	21	;save in list
		movwf fib2
		movwf	22	;save in list
		movlw 3	
		movwf counter	;have preloaded the first three numbers, so start at 3
		movlw	23	;Initialise File Select Register, with next location for 
		movwf	fsr	   ;list of numbers to be saved
;
forward movf  fib1,0
		addwf fib2,0
		btfsc status,c	;test if we have overflowed 8-bit range
		goto  reverse	;here if we have overflowed, hence reverse down the series
		movwf fibtemp	;latest number now placed in fibtemp
		movwf indf		;save by indirect addressing
		movf  fsr,0		;test to see if FSR is at top of available range
		sublw 30
		btfss status,z
		incf  fsr,1		;increment FSR, if available range not full
		incf  counter,1
;now shuffle numbers held, discarding the oldest
		movf  fib1,0 	;first move middle number, to overwrite oldest
		movwf fib0
		movf  fib2,0
		movwf fib1
		movf  fibtemp,0
		movwf fib2
		goto  forward
;when reversing down, we will subtract fib0 from fib1 to form new fib0
reverse movf  fib0,0
		subwf fib1,0
		movwf fibtemp		;latest number now placed in fibtemp
		decf  counter,1
;now shuffle numbers held, discarding the oldest
		movf fib1,0 	;first move middle number, to overwrite oldest
		movwf fib2
		movf fib0,0
		movwf fib1
		movf fibtemp,0
		movwf fib0
;test if counter has reached 3, in which case return to forward
		movf  counter,0 
		sublw 3
		btfsc status,z
loop	goto  loop		;just loop if finished
		goto  reverse
;
		end
		

