OPTION EXPLICIT
OPTION AUTORUN ON
CONST TCR_ADDRESS = 12
CONST TIMEOUT = 2000
DIM LAST_CODE AS STRING
DIM CURRENT_CODE AS STRING
DIM KEY AS STRING
DIM LAST_UPDATE AS INTEGER
SETPIN GP0, GP1, I2C
I2C OPEN 100,100	''should work at 400kHz, too
PRINT "START"
PRINT "THE TINY CODE READER SHOULD BE AT ADDRESS &H0C"
I2CSCAN
PRINT "PRESS 0 OR 1 TO TURN LED OFF OR ON"

DO 
	CURRENT_CODE=CHECK_READER()
	IF (LAST_CODE <> CURRENT_CODE) OR ((TIMER-LAST_UPDATE)>TIMEOUT) THEN
		IF LEN(CURRENT_CODE)>0 THEN
			PRINT "CODE RECEIVED (" +STR$(LEN(CURRENT_CODE))+" bytes):"
			PRINT CURRENT_CODE
		ELSE
			IF MM.I2C = 0 THEN
				PRINT "NO CODE."
			ELSE
				PRINT "COMMS ERROR."
			ENDIF
		ENDIF
		LAST_UPDATE=TIMER 
		LAST_CODE=CURRENT_CODE
	ENDIF
	KEY = INKEY$
	IF KEY = "0" THEN PRINT "LED OFF": LED_OFF
	IF KEY = "1" THEN PRINT "LED ON": LED_ON
	PAUSE 100
LOOP

FUNCTION CHECK_READER() AS STRING
	STATIC RECV_BUF AS STRING
	STATIC L AS INTEGER
	I2C READ TCR_ADDRESS,0,254,RECV_BUF
	'PRINT LEN(RECV_BUF)
	L=ASC(MID$(RECV_BUF,1,1))+256*ASC(MID$(RECV_BUF,2,1))
	IF L > 252 THEN L = 252
	CHECK_READER=MID$(RECV_BUF,3,L)
	'PRINT LEN(CHECK_READER)
END FUNCTION

SUB LED_OFF
	I2C WRITE TCR_ADDRESS, 0, 2,1,0
END SUB

SUB LED_ON
	I2C WRITE TCR_ADDRESS, 0, 2,1,1
END SUB

SUB I2CSCAN
	LOCAL I AS INTEGER
	LOCAL J AS INTEGER
	J=0
	PRINT "    x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF";
	FOR I = 0 TO 111
		IF (I MOD 16) = 0 THEN PRINT:PRINT HEX$(I\16)+"x  ";		''new line and header
		IF I<8 THEN
			PRINT "   ";
		ELSE
			I2C CHECK I
			IF MM.I2C = 0 THEN	''0=OK
				PRINT RIGHT$("00" + HEX$(I) +" ",3);
				J=J+1
			ELSE
				PRINT ".. ";
			ENDIF
		ENDIF
	NEXT I
	PRINT
	IF J=1 THEN
		PRINT "1 DEVICE FOUND."
	ELSE	
		PRINT STR$(J)+" DEVICES FOUND."
	ENDIF
END SUB
