;******************************************************************************
;Fibo_18
;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. 
;Program intended for simulation only, hence no input/output.
;The program demonstrates addition, compare. 
;TJW 10.0.05
;******************************************************************************

	list p=18F242
	#include P18F242.inc
;no i/o ports used

;these memory locations hold 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 1 

	org 00
;Initialse BSR
		movlb 01	;clear BSR
;preload initial values
		movlw 0
		movwf fib0,1
		movlw 1
		movwf fib1,1
		movwf fib2,1
		movlw 3	
		movwf counter,1	;we have preloaded the first three numbers, so start at 2
;
forward movf  fib1,0,1
		addwf fib2,0,1
		bc	reverse
;		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,1	;latest number now placed in fibtemp
		incf  counter,1,1
;now shuffle numbers held, discarding the oldest
		movff	fib1,fib0
		movff	fib2,fib1
		movff	fibtemp,fib2
;		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
		movff	fib1,fib2
  		movff	fib0,fib1
  		movff	fibtemp,fib0
;		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
		movlw 3
		cpfseq counter
		goto reverse
		goto  forward
;		btfsc status,z
;		goto  forward
;		goto  reverse
;
		end
		

