import struct
import wiringpi
import time



def ISR():
	wiringpi.digitalWrite(16, 1)



wiringpi.wiringPiSetupGpio()
SPIchan = 0
SPIspeed = 1000000
wiringpi.wiringPiSPISetup (SPIchan, SPIspeed)
wiringpi.pinMode(16, wiringpi.OUTPUT)
wiringpi.digitalWrite(16, 0)
wiringpi.pinMode(19, wiringpi.INPUT)
wiringpi.wiringPiISR(19, wiringpi.INT_EDGE_FALLING, ISR)



clr_mdr0 = 0b00001000
clr_mdr1 = 0b00010000
clr_cntr = 0b00100000
clr_str  = 0b00110000

rd_cntr  = 0x60
rd_otr  = 0x68

rd_str = 0x70
rd_mdr0 = 0x48
rd_mdr1 = 0x50

load_cntr2otr = 0b11100000


def write(c):
  buf = bytes([c])
  retlen, retdata = wiringpi.wiringPiSPIDataRW(SPIchan, buf)

def read5(c):
  buf = bytes([c,0,0,0,0])
  retlen, retdata = wiringpi.wiringPiSPIDataRW(SPIchan, buf)
  v = struct.unpack('>I', retdata[1:])[0]
  return v

def read2(c):
  buf = bytes([c,0])
  retlen, retdata = wiringpi.wiringPiSPIDataRW(SPIchan, buf)
  v = struct.unpack('>B', retdata[1:])[0]
  return v



#write(clr_mdr0)
#write(clr_mdr1)
#write(clr_cntr)


write(clr_cntr)
write(clr_str)


while True:
	x = read2(rd_str)
	y = read5(rd_cntr)

	print("{0} {0:#04x} {0:#010b}".format(x))
	print(y)
	print

	time.sleep(1.0)