
#include "8051equ.inc"

.org	00h
	ajmp	start

.org	0bh
	reti

.org	13h
	reti

.org	1bh
	reti

.org	23h
	reti

.org	25h


initialize:
	; start timer 0 - 16 bit timer mode
	mov	TMOD, #01h
	setb	TR0

	mov	PSW, #00h
	mov	IE, #00h
	ret

; delay for 1 ms (11.0592 MHz crystal)
delay_ms:
	mov	r7, #00h
loop_1:
	inc	r7
	mov	a, r7
	cjne	a, #0ffh, loop_1
	ret

; 8-bit binary to bcd converter
; a  - input value
; r2 - output digit 1
; r3 - output digit 2
; r4 - output digit 3
bin_to_bcd:

	mov	B, #010d
	div	ab
	mov	r4, B
	mov	B, #010d
	div	ab
	mov	r3, B
	mov	B, #010d
	div	ab
	mov	r2, B
	ret

segment_table:	
	.db 	00001001b, 11101011b, 01000101b, 01100001b, 10100011b, 00110001b, 00010001b, 01101011b, 00000001b, 00100011b

; display 3 digit BCD number in the A register
display_bcd:
	mov	dptr, #segment_table
	movc	a, @a+dptr
	mov	P1, a
	ret
		
start:
	acall	initialize

	; set P3.0 to be used as an input
	setb	P3.0	

	; wait until switch is pressed (and debounce)
wait1:
	acall	delay_ms
	jb	P3.0, wait1

random:
	mov	a, TL0

	; wait for switch to be released (and debounce)
wait2:
	mov	20h, a
	acall	delay_ms
	mov	a, 20h
	jnb	P3.0, wait2
	acall	bin_to_bcd

display_loop:
	mov	a, r2
	acall	display_bcd
	setb	P3.3
	acall	delay_ms
	clr	P3.3

	mov	a, r3
	acall	display_bcd
	setb	P3.4
	acall	delay_ms
	clr	P3.4

	mov	a, r4
	acall	display_bcd
	setb	P3.5
	acall	delay_ms
	clr	P3.5

	; display same number until switch is pressed
	jb	P3.0, display_loop
	ajmp	random
	
.end
