PIC Microcontoller Math Method

12 Bit Square Root

;**********************************************************************
;by Nikolai Golovchenko
;12 bit SQARE ROOT
;Input:
;ACCB0 - high byte
;ACCB1 - low byte
;Result:
;ACCB0 - 6bit
;Used:
;TEMPB0 - temporary for result
;TEMPB1 - temporary for input
;LOOPCNT - counter
;Memory used
;32 instructions
;5 RAM bytes
;11+17*5 + 16 + 6 = 118 cycles all cases
;**********************************************************************
Sqrt12	clr	TEMPB0	;clear all used
	clr	TEMPB1	;temporary registers
	mov	W, #6	;and setup counter
	mov	LOOPCNT, W	;

	swap	ACCB0	;Left justify
	mov	W, <>ACCB1	;12bit value
	and	W, #$0f	;in two byte
	or	ACCB0, W	;accumulator
	mov	W, <>ACCB1	;
	and	W, #$f0	;
	mov	ACCB1, W	;
Sqrt12a
	rl	ACCB1	;shift next
	rl	ACCB0	;two higher bits
	rl	TEMPB1	;of input
	rl	ACCB1	;to
	rl	ACCB0	;TEMPB1
	rl	TEMPB1	;

	mov	W, TEMPB0	;take current result (shifted 2 bits left)
;*** WARNING: ADDLW was expanded in three instructions! Check if previous instruction is a skip instruction. 
;	addlw 0x01	;and OR with 01 (test bit) - addlw clears C
	mov	Hack, W
	mov	W, #$01	;and OR with 01 (test bit) - addlw clears C
	add	W, Hack
	rl	TEMPB0	;and reserve place for the next bit

	mov	W, TEMPB1-w	;test substraction for borrow
	snb	C
	setb	TEMPB0.2	;set next result bit if no borrow
	snb	C
	mov	TEMPB1, W	;store substraction result if no borrow

	decsz	LOOPCNT	;repeat untill all 6 bits will be found
	jmp	Sqrt12a

	clrb	C
	rr	TEMPB0	;right
	mov	W, >>TEMPB0	;justify the result
	mov	ACCB0, W	;and copy to result register
	ret
;**********************************************************************
;Last updated 16Nov99