	

#define STACK_TOP 0xffefac	
		
	.text
	.org 0
	.h8300s
	
	.globl start
start:
	mov.l #STACK_TOP, er7

	jsr pins_init
	jsr serial_init
			
loop:		
	mov.l #0x100000, er2

loop_delay:

	jsr serial_rx_check
	beq dont_echo
	
	jsr serial_rx
	jsr serial_tx
			
dont_echo:	
	
	sub.l #0x0001, er2
	bne loop_delay

	jsr pins_led_toggle

	mov.b #'A', r0l
	jsr serial_tx
		
	bra loop


#define P1DDR  0xfe30:16
#define P1DR   0x00:8 /* same as 0xff00:16 */
#define P1DATA 0xb0:8 /* same as 0xffb0:16 */

#define P1_PIN_PMODE   0x80
#define P1_PIN_USERLED 0x20

pins_init:	
	mov.b #(P1_PIN_PMODE + P1_PIN_USERLED), r0l   /* pins are outputs */
	mov.b #P1_PIN_USERLED, r1l   
	mov.b r0l, @P1DDR
	mov.b r1l, @P1DR
	rts			
	
pins_led_toggle:	
	mov.b @P1DATA, r0l
	xor.b #P1_PIN_USERLED, r0l
	mov.b r0l, @P1DR
	rts
	
			
#define SMR2  0x88:8
#define BRR2  0x89:8
#define SCR2  0x8a:8
#define TDR2  0x8b:8
#define SSR2  0x8c:8
#define RDR2  0x8d:8
#define SCMR2 0x8e:8

#define SMR  SMR2
#define BRR  BRR2
#define SCR  SCR2
#define TDR  TDR2
#define SSR  SSR2
#define RDR  RDR2
#define SCMR SCMR2

#define BOARD_XIN 18432000	
#define BOARD_BRR_9600 58

serial_init:	
	
	/* setup the serial controller to n81 and clock/1 */
	
	mov.b #0, r0l      
	mov.b r0l, @SMR

	/* setup the clock generator to 9600bps */
	
	mov.b #BOARD_BRR_9600, r0l      
	mov.b r0l, @BRR
	
	/* enable transmit and receive, no interrupts */
	
	mov.b #0x30, r0l
	mov.b r0l, @SCR

	rts

serial_tx:			
	/* send a character passed in r0l*/
	
serial_tx_drain:	
	btst #7, @SSR
	beq serial_tx_drain
	
	mov.b r0l, @TDR
	bclr #7, @SSR

serial_tx_finish:	
	btst #2, @SSR
	beq serial_tx_finish

	rts	

serial_rx:
	/* receive a character and return in r0l */

serial_rx_wait:	
	btst #6, @SSR
	beq serial_rx_wait

	mov.b @RDR, r0l
	bclr #6, @SSR
	
	rts

serial_rx_check:
	/* check if data is available - z-flag is cleared if available */
	btst #6, @SSR
	rts


	