 TITLE  "photo3.asm"            	; sunflower robot
 List P=12F675, R=DEC
 INCLUDE "p12F675.inc"

; data segment
 CBLOCK 0x20                   
 del  					; variable used for delays 
 n1, n2					; sensor values
 ENDC

; code segment
 PAGE
; __CONFIG _BODEN_OFF & _CPD_OFF & _CP_OFF & _MCLRE_OFF & _PWRTE_ON & _WDT_OFF & _INTRC_OSC_NOCLKOUT
 __CONFIG b'110000100'			; binary version of config 
  org 0                      		; start program at the beginning of mem
	nop
	bcf	STATUS, RP0 		; activale BANK 0
	clrf	GPIO			; initialize GPIO
	clrf 	INTCON			; disable all interrupts
	movlw	0x07
	movwf	CMCON			; comparator OFF
	clrf	ADCON0			; ADC OFF
  	bsf    	STATUS, RP0      	; change to BANK 1
	clrf	ANSEL ^ 0x80 		; turn off ADC
	clrf	PIE1 ^ 0x80		; disable external interrupts
	clrf	IOC 			; disable interrupt on change	
	clrf	WPU
	bsf	OPTION_REG ^0x80, 7 	; disable pull-ups 
	movlw	0x0A
	movwf	TRISIO ^ 0x80		; enable GP<3,1> for input
  	bcf    	STATUS, RP0        	; back to BANK 0

loop
	call 	measure			; get n1 and n2

	movlw	b'001010'		; take caps low and turn off the motor
	andwf	GPIO, f

	movf	n2, w			; w = n1 - n2
	subwf	n1, w			
	btfss	STATUS, C
	sublw	0			; w = |n1 - n2|
	sublw	15			; w = 15 - w
	btfsc	STATUS, C		
	goto 	L2			; diff is small - continue

	movf	n2, w
	subwf	n1, w
	btfss	STATUS, C
	goto 	L1	
	bsf	GPIO, 0
	goto 	L2
L1	bsf	GPIO, 5

L2	movlw	50			; 50 msec delay
	movwf	del
	call	delay
  	goto 	loop			; endless loop


; procedures
delay					; a delay for del milliseconds
	movlw 	200
	
	sublw	1			; this loop takes 5us*200 = 1ms
	sublw	0			; for PIC12F675 @ 4 Mhz
	btfss	STATUS, Z
	goto 	$-3

	decfsz	del, f
	goto 	delay
	return

measure					; read light sensors
	clrf	n1		
	movlw	b'10000'		; take cap high
	iorwf	GPIO, f
		
M1	incf	n1, f			; start the first light measurement
 	movlw	255
	subwf	n1, w
	btfsc	STATUS, Z
	goto	M2
	btfsc	GPIO, 3			; is input low ?
	goto	M1			; back to loop


M2	clrf	n2
	movlw	b'100'			; take cap high
	iorwf	GPIO, f
	
M3	incf	n2, f			; start the second measurement
 	movlw	255
	subwf	n2, w
	btfsc	STATUS, Z
	goto	M4
	btfsc	GPIO, 1			; is input low ?
	goto	M3			; back to loop

M4	return

 end
