Commit 1f6c417c authored by Paolo Baesso's avatar Paolo Baesso Committed by GitHub

Merge pull request #5 from PaoloGB/development

Development
parents 781e2353 cdd187e7
......@@ -45,20 +45,20 @@ class EUDETdummy:
self.IC6=PCA9539PW(self.TLU_I2C, 0x74)
self.IC6.setInvertReg(0, 0x00)# 0= normal, 1= inverted
self.IC6.setIOReg(0, 0x00)# 0= output, 1= input
self.IC6.setOutputs(0, 0x77)# If output, set to XX
self.IC6.setOutputs(0, 0xAA)# If output, set to XX
self.IC6.setInvertReg(1, 0x00)# 0= normal, 1= inverted
self.IC6.setIOReg(1, 0x00)# 0= output, 1= input
self.IC6.setOutputs(1, 0x77)# If output, set to XX
self.IC6.setOutputs(1, 0xAA)# If output, set to XX
self.IC7=PCA9539PW(self.TLU_I2C, 0x75)
self.IC7.setInvertReg(0, 0x00)# 0= normal, 1= inverted
self.IC7.setIOReg(0, 0x00)# 0= output, 1= input
self.IC7.setOutputs(0, 0x00)# If output, set to XX
self.IC7.setOutputs(0, 0x0F)# If output, set to XX
self.IC7.setInvertReg(1, 0x00)# 0= normal, 1= inverted
self.IC7.setIOReg(1, 0x00)# 0= output, 1= input
self.IC7.setOutputs(1, 0xB0)# If output, set to XX
self.IC7.setOutputs(1, 0x50)# If output, set to XX
##################################################################################################################################
......
This diff is collapsed.
This diff is collapsed.
# -*- coding: utf-8 -*-
import uhal
from I2CuHal import I2CCore
import StringIO
class AD5665R:
#Class to configure the DAC modules
def __init__(self, i2c, slaveaddr=0x1F):
self.i2c = i2c
self.slaveaddr = slaveaddr
def setIntRef(self, intRef=False, verbose=False):
mystop=True
if intRef:
cmdDAC= [0x38,0x00,0x01]
else:
cmdDAC= [0x38,0x00,0x00]
self.i2c.write( self.slaveaddr, cmdDAC, mystop)
if verbose:
print "DAC int ref:", intRef
def writeDAC(self, dacCode, channel, verbose=False):
#Vtarget is the required voltage, channel is the DAC channel to target
#intRef indicates whether to use the external voltage reference (True)
#or the internal one (False).
print "\tDAC value:" , hex(dacCode)
if channel<0 or channel>7:
print "writeDAC ERROR: channel",channel,"not in range 0-7 (bit mask)"
return -1
if dacCode<0:
print "writeDAC ERROR: value",dacCode,"<0. Default to 0"
dacCode=0
elif dacCode>0xFFFF :
print "writeDAC ERROR: value",dacCode,">0xFFFF. Default to 0xFFFF"
dacCode=0xFFFF
sequence=[( 0x18 + ( channel &0x7 ) ) , int(dacCode/256)&0xff , int(dacCode)&0xff]
print "\tWriting DAC string:", sequence
mystop= False
self.i2c.write( self.slaveaddr, sequence, mystop)
# -*- coding: utf-8 -*-
import uhal
from I2CuHal import I2CCore
import time
#import miniTLU
from si5345 import si5345
from AD5665R import AD5665R
from PCA9539PW import PCA9539PW
from E24AA025E48T import E24AA025E48T
manager = uhal.ConnectionManager("file://./TLUconnection.xml")
hw = manager.getDevice("tlu")
# hw.getNode("A").write(255)
reg = hw.getNode("version").read()
hw.dispatch()
print "CHECK REG= ", hex(reg)
# #First I2C core
print ("Instantiating master I2C core:")
master_I2C= I2CCore(hw, 10, 5, "i2c_master", None)
master_I2C.state()
#
# #######################################
enableCore= True #Only need to run this once, after power-up
if (enableCore):
mystop=True
print " Write RegDir to set I/O[7] to output:"
myslave= 0x21
mycmd= [0x01, 0x7F]
nwords= 1
master_I2C.write(myslave, mycmd, mystop)
mystop=False
mycmd= [0x01]
master_I2C.write(myslave, mycmd, mystop)
res= master_I2C.read( myslave, nwords)
print "\tPost RegDir: ", res
# #######################################
#
# time.sleep(0.1)
# #Read the EPROM
# mystop=False
# nwords=6
# myslave= 0x53 #DUNE EPROM 0x53 (Possibly)
# myaddr= [0xfa]#0xfa
# master_I2C.write( myslave, myaddr, mystop)
# #res= master_I2C.read( 0x50, 6)
# res= master_I2C.read( myslave, nwords)
# print " PCB EPROM: "
# result="\t "
# for iaddr in res:
# result+="%02x "%(iaddr)
# print result
# #######################################
#Second I2C core
#print ("Instantiating SFP I2C core:")
#clock_I2C= I2CCore(hw, 10, 5, "i2c_sfp", None)
#clock_I2C.state()
# #Third I2C core
# print ("Instantiating clock I2C core:")
# clock_I2C= I2CCore(hw, 10, 5, "i2c_clk", None)
# clock_I2C.state()
# #time.sleep(0.01)
# #Read the EPROM
# mystop=False
# nwords=2
# myslave= 0x68 #DUNE CLOCK CHIP 0x68
# myaddr= [0x02 ]#0xfa
# clock_I2C.write( myslave, myaddr, mystop)
# #time.sleep(0.1)
# res= clock_I2C.read( myslave, nwords)
# print " CLOCK EPROM: "
# result="\t "
# for iaddr in res:
# result+="%02x "%(iaddr)
# print result
#
#CLOCK CONFIGURATION BEGIN
zeClock=si5345(master_I2C, 0x68)
res= zeClock.getDeviceVersion()
zeClock.checkDesignID()
#zeClock.setPage(0, True)
#zeClock.getPage(True)
clkRegList= zeClock.parse_clk("./../../bitFiles/TLU_CLK_Config.txt")
zeClock.writeConfiguration(clkRegList)######
zeClock.writeRegister(0x0536, [0x0B]) #Configures manual switch of inputs
zeClock.writeRegister(0x0949, [0x0F]) #Enable all inputs
zeClock.writeRegister(0x052A, [0x05]) #Configures source of input
iopower= zeClock.readRegister(0x0949, 1)
print " Clock IO power: 0x%X" % iopower[0]
lol= zeClock.readRegister(0x000E, 1)
print " Clock LOL: 0x%X" % lol[0]
los= zeClock.readRegister(0x000D, 1)
print " Clock LOS: 0x%X" % los[0]
#CLOCK CONFIGURATION END
#DAC CONFIGURATION BEGIN
zeDAC1=AD5665R(master_I2C, 0x13)
zeDAC1.setIntRef(intRef= False, verbose= True)
zeDAC1.writeDAC(0x0, 7, verbose= True)#7626
zeDAC2=AD5665R(master_I2C, 0x1F)
zeDAC2.setIntRef(intRef= False, verbose= True)
zeDAC2.writeDAC(0x2fff, 3, verbose= True)
#DAC CONFIGURATION END
#EEPROM BEGIN
zeEEPROM= E24AA025E48T(master_I2C, 0x50)
res=zeEEPROM.readEEPROM(0xfa, 6)
result=" EEPROM ID:\n\t"
for iaddr in res:
result+="%02x "%(iaddr)
print result
#EEPROM END
# #I2C EXPANDER CONFIGURATION BEGIN
IC6=PCA9539PW(master_I2C, 0x74)
#BANK 0
IC6.setInvertReg(0, 0x00)# 0= normal
IC6.setIOReg(0, 0xFF)# 0= output <<<<<<<<<<<<<<<<<<<
IC6.setOutputs(0, 0xFF)
res= IC6.getInputs(0)
print "IC6 read back bank 0: 0x%X" % res[0]
#
#BANK 1
IC6.setInvertReg(1, 0x00)# 0= normal
IC6.setIOReg(1, 0xFF)# 0= output <<<<<<<<<<<<<<<<<<<
IC6.setOutputs(1, 0xFF)
res= IC6.getInputs(1)
print "IC6 read back bank 1: 0x%X" % res[0]
# # #
IC7=PCA9539PW(master_I2C, 0x75)
#BANK 0
IC7.setInvertReg(0, 0xFF)# 0= normal
IC7.setIOReg(0, 0xFA)# 0= output <<<<<<<<<<<<<<<<<<<
IC7.setOutputs(0, 0xFF)
res= IC7.getInputs(0)
print "IC7 read back bank 0: 0x%X" % res[0]
#
#BANK 1
IC7.setInvertReg(1, 0x00)# 0= normal
IC7.setIOReg(1, 0x0F)# 0= output <<<<<<<<<<<<<<<<<<<
IC7.setOutputs(1, 0xFF)
res= IC7.getInputs(1)
print "IC7 read back bank 1: 0x%X" % res[0]
# #I2C EXPANDER CONFIGURATION END
# #Reset counters
#cmd = int("0x0", 16) #write 0x2 to reset
#hw.getNode("triggerInputs.SerdesRstW").write(cmd)
#restatus= hw.getNode("triggerInputs.SerdesRstR").read()
#hw.dispatch()
#print "Trigger Reset: 0x%X" % restatus
## #Read trigger inputs
#myreg= [-1, -1, -1, -1, -1, -1]
#for inputN in range(0, 6):
# regString= "triggerInputs.ThrCount%dR" % inputN
# myreg[inputN]= hw.getNode(regString).read()
# hw.dispatch()
# print regString, myreg[inputN]
## Read ev formatter
#cmd = int("0x0", 16) #
##hw.getNode("Event_Formatter.Enable_Record_Data").write(cmd)
#efstatus= hw.getNode("Event_Formatter.CurrentTimestampLR").read()
#hw.dispatch()
#print "Event Formatter Record: 0x%X" % efstatus
# -*- coding: utf-8 -*-
import uhal
from I2CuHal import I2CCore
import StringIO
class E24AA025E48T:
#Class to configure the EEPROM
def __init__(self, i2c, slaveaddr=0x50):
self.i2c = i2c
self.slaveaddr = slaveaddr
def readEEPROM(self, startadd, nBytes):
#Read EEPROM memory locations
mystop= False
myaddr= [startadd]#0xfa
self.i2c.write( self.slaveaddr, [startadd], mystop)
res= self.i2c.read( self.slaveaddr, nBytes)
return res
import time
#from PyChipsUser import *
from I2cBusProperties import *
from RawI2cAccess import *
class FmcTluI2c:
############################
### configure i2c connection
############################
def __init__(self,board):
self.board = board
i2cClockPrescale = 0x30
self.i2cBusProps = I2cBusProperties(self.board, i2cClockPrescale)
return
##########################
### scan all i2c addresses
##########################
def i2c_scan(self):
list=[]
for islave in range(128):
i2cscan = RawI2cAccess(self.i2cBusProps, islave)
try:
i2cscan.write([0x00])
device="slave address "+hex(islave)+" "
if islave==0x1f:
device+="(DAC)"
elif islave==0x50:
device+="(serial number PROM)"
elif islave>=0x54 and islave<=0x57:
device+="(sp601 onboard EEPROM)"
else:
device+="(???)"
pass
list.append(device)
pass
except:
pass
pass
return list
###################
### write to EEPROM
###################
def eeprom_write(self,address,value):
if address<0 or address>127:
print "eeprom_write ERROR: address",address,"not in range 0-127"
return
if value<0 or value>255:
print "eeprom_write ERROR: value",value,"not in range 0-255"
return
i2cSlaveAddr = 0x50 # seven bit address, binary 1010000
prom = RawI2cAccess(self.i2cBusProps, i2cSlaveAddr)
prom.write([address,value])
time.sleep(0.01) # write cycle time is 5ms. let's wait 10 to make sure.
return
####################
### read from EEPROM
####################
def eeprom_read(self,address):
if address<0 or address>255:
print "eeprom_write ERROR: address",address,"not in range 0-127"
return
i2cSlaveAddr = 0x50 # seven bit address, binary 1010000
prom = RawI2cAccess(self.i2cBusProps, i2cSlaveAddr)
prom.write([address])
return prom.read(1)[0]
######################
### read serial number
######################
def get_serial_number(self):
result=""
for iaddr in [0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff]:
result+="%02x "%(self.eeprom_read(iaddr))
pass
return result
#################
### set DAC value
#################
def set_dac(self,channel,value , vrefOn = 0 , i2cSlaveAddrDac = 0x1F):
if channel<0 or channel>7:
print "set_dac ERROR: channel",channel,"not in range 0-7 (bit mask)"
return -1
if value<0 or value>0xFFFF:
print "set_dac ERROR: value",value,"not in range 0-0xFFFF"
return -1
# AD5665R chip with A0,A1 tied to ground
#i2cSlaveAddrDac = 0x1F # seven bit address, binary 00011111
print "I2C address of DAC = " , hex(i2cSlaveAddrDac)
dac = RawI2cAccess(self.i2cBusProps, i2cSlaveAddrDac)
# if we want to enable internal voltage reference:
if vrefOn:
# enter vref-on mode:
print "Turning internal reference ON"
dac.write([0x38,0x00,0x01])
else:
print "Turning internal reference OFF"
dac.write([0x38,0x00,0x00])
# now set the actual value
sequence=[( 0x18 + ( channel &0x7 ) ) , (value/256)&0xff , value&0xff]
print sequence
dac.write(sequence)
##################################################
### convert required threshold voltage to DAC code
##################################################
def convert_voltage_to_dac(self, desiredVoltage, Vref=1.300):
Vdaq = ( desiredVoltage + Vref ) / 2
dacCode = 0xFFFF * Vdaq / Vref
return int(dacCode)
##################################################
### calculate the DAC code required and set DAC
##################################################
def set_threshold_voltage(self, channel , voltage ):
dacCode = self.convert_voltage_to_dac(voltage)
print " requested voltage, calculated DAC code = " , voltage , dacCode
self.set_dac(channel , dacCode)
# -*- coding: utf-8 -*-
"""
"""
import time
import uhal
verbose = True
################################################################################
# /*
# I2C CORE
# */
################################################################################
class I2CCore:
"""I2C communication block."""
# Define bits in cmd_stat register
startcmd = 0x1 << 7
stopcmd = 0x1 << 6
readcmd = 0x1 << 5
writecmd = 0x1 << 4
ack = 0x1 << 3
intack = 0x1
recvdack = 0x1 << 7
busy = 0x1 << 6
arblost = 0x1 << 5
inprogress = 0x1 << 1
interrupt = 0x1
def __init__(self, target, wclk, i2cclk, name="i2c", delay=None):
self.target = target
self.name = name
self.delay = delay
self.prescale_low = self.target.getNode("%s.i2c_pre_lo" % name)
self.prescale_high = self.target.getNode("%s.i2c_pre_hi" % name)
self.ctrl = self.target.getNode("%s.i2c_ctrl" % name)
self.data = self.target.getNode("%s.i2c_rxtx" % name)
self.cmd_stat = self.target.getNode("%s.i2c_cmdstatus" % name)
self.wishboneclock = wclk
self.i2cclock = i2cclk
self.config()
def state(self):
status = {}
status["ps_low"] = self.prescale_low.read()
status["ps_hi"] = self.prescale_high.read()
status["ctrl"] = self.ctrl.read()
status["data"] = self.data.read()
status["cmd_stat"] = self.cmd_stat.read()
self.target.dispatch()
status["prescale"] = status["ps_hi"] << 8
status["prescale"] |= status["ps_low"]
for reg in status:
val = status[reg]
bval = bin(int(val))
if verbose:
print "\treg %s = %d, 0x%x, %s" % (reg, val, val, bval)
def clearint(self):
self.ctrl.write(0x1)
self.target.dispatch()
def config(self):
#INITIALIZATION OF THE I2S MASTER CORE
#Disable core
self.ctrl.write(0x0 << 7)
self.target.dispatch()
#Write pre-scale register
#prescale = int(self.wishboneclock / (5.0 * self.i2cclock)) - 1
prescale = 0x0100 #FOR NOW HARDWIRED, TO BE MODIFIED
#prescale = 0x2710 #FOR NOW HARDWIRED, TO BE MODIFIED
self.prescale_low.write(prescale & 0xff)
self.prescale_high.write((prescale & 0xff00) >> 8)
#Enable core
self.ctrl.write(0x1 << 7)
self.target.dispatch()
def checkack(self):
inprogress = True
ack = False
while inprogress:
cmd_stat = self.cmd_stat.read()
self.target.dispatch()
inprogress = (cmd_stat & I2CCore.inprogress) > 0
ack = (cmd_stat & I2CCore.recvdack) == 0
return ack
def delayorcheckack(self):
ack = True
if self.delay is None:
ack = self.checkack()
else:
time.sleep(self.delay)
ack = self.checkack()#Remove this?
return ack
################################################################################
# /*
# I2C WRITE
# */
################################################################################
def write(self, addr, data, stop=True):
"""Write data to the device with the given address."""
# Start transfer with 7 bit address and write bit (0)
nwritten = -1
addr &= 0x7f
addr = addr << 1
startcmd = 0x1 << 7
stopcmd = 0x1 << 6
writecmd = 0x1 << 4
#Set transmit register (write operation, LSB=0)
self.data.write(addr)
#Set Command Register to 0x90 (write, start)
self.cmd_stat.write(I2CCore.startcmd | I2CCore.writecmd)
self.target.dispatch()
ack = self.delayorcheckack()
if not ack:
self.cmd_stat.write(I2CCore.stopcmd)
self.target.dispatch()
return nwritten
nwritten += 1
for val in data:
val &= 0xff
#Write slave memory address
self.data.write(val)
#Set Command Register to 0x10 (write)
self.cmd_stat.write(I2CCore.writecmd)
self.target.dispatch()
ack = self.delayorcheckack()
if not ack:
self.cmd_stat.write(I2CCore.stopcmd)
self.target.dispatch()
return nwritten
nwritten += 1
if stop:
self.cmd_stat.write(I2CCore.stopcmd)
self.target.dispatch()
return nwritten
################################################################################
# /*
# I2C READ
# */
################################################################################
def read(self, addr, n):
"""Read n bytes of data from the device with the given address."""
# Start transfer with 7 bit address and read bit (1)
data = []
addr &= 0x7f
addr = addr << 1
addr |= 0x1 # read bit
self.data.write(addr)
self.cmd_stat.write(I2CCore.startcmd | I2CCore.writecmd)
self.target.dispatch()
ack = self.delayorcheckack()
if not ack:
self.cmd_stat.write(I2CCore.stopcmd)
self.target.dispatch()
return data
for i in range(n):
if i < (n-1):
self.cmd_stat.write(I2CCore.readcmd) # <---
else:
self.cmd_stat.write(I2CCore.readcmd | I2CCore.ack | I2CCore.stopcmd) # <--- This tells the slave that it is the last word
self.target.dispatch()
ack = self.delayorcheckack()
val = self.data.read()
self.target.dispatch()
data.append(val & 0xff)
#self.cmd_stat.write(I2CCore.stopcmd)
#self.target.dispatch()
return data
################################################################################
# /*
# I2C WRITE-READ
# */
################################################################################
# def writeread(self, addr, data, n):
# """Write data to device, then read n bytes back from it."""
# nwritten = self.write(addr, data, stop=False)
# readdata = []
# if nwritten == len(data):
# readdata = self.read(addr, n)
# return nwritten, readdata
"""
SPI core XML:
<node description="SPI master controller" fwinfo="endpoint;width=3">
<node id="d0" address="0x0" description="Data reg 0"/>
<node id="d1" address="0x1" description="Data reg 1"/>
<node id="d2" address="0x2" description="Data reg 2"/>
<node id="d3" address="0x3" description="Data reg 3"/>
<node id="ctrl" address="0x4" description="Control reg"/>
<node id="divider" address="0x5" description="Clock divider reg"/>
<node id="ss" address="0x6" description="Slave select reg"/>
</node>
"""
class SPICore:
go_busy = 0x1 << 8
rising = 1
falling = 0
def __init__(self, target, wclk, spiclk, basename="io.spi"):
self.target = target
# Only a single data register is required since all transfers are
# 16 bit long
self.data = target.getNode("%s.d0" % basename)
self.control = target.getNode("%s.ctrl" % basename)
self.control_val = 0b0
self.divider = target.getNode("%s.divider" % basename)
self.slaveselect = target.getNode("%s.ss" % basename)
self.divider_val = int(wclk / spiclk / 2.0 - 1.0)
self.divider_val = 0x7f
self.configured = False
def config(self):
"Configure SPI interace for communicating with ADCs."
self.divider_val = int(self.divider_val) % 0xffff
if verbose:
print "Configuring SPI core, divider = 0x%x" % self.divider_val
self.divider.write(self.divider_val)
self.target.dispatch()
self.control_val = 0x0
self.control_val |= 0x0 << 13 # Automatic slave select
self.control_val |= 0x0 << 12 # No interrupt
self.control_val |= 0x0 << 11 # MSB first
# ADC samples data on rising edge of SCK
self.control_val |= 0x1 << 10 # change ouput on falling edge of SCK
# ADC changes output shortly after falling edge of SCK
self.control_val |= 0x0 << 9 # read input on rising edge
self.control_val |= 0x10 # 16 bit transfers
if verbose:
print "SPI control val = 0x%x = %s" % (self.control_val, bin(self.control_val))
self.configured = True
def transmit(self, chip, value):
if not self.configured:
self.config()
assert chip >= 0 and chip < 8
value &= 0xffff
self.data.write(value)
checkdata = self.data.read()
self.target.dispatch()
assert checkdata == value
self.control.write(self.control_val)
self.slaveselect.write(0xff ^ (0x1 << chip))
self.target.dispatch()
self.control.write(self.control_val | SPICore.go_busy)
self.target.dispatch()
busy = True
while busy:
status = self.control.read()
self.target.dispatch()
busy = status & SPICore.go_busy > 0
self.slaveselect.write(0xff)
data = self.data.read()
ss = self.slaveselect.read()
status = self.control.read()
self.target.dispatch()
#print "Received data: 0x%x, status = 0x%x, ss = 0x%x" % (data, status, ss)
return data
##########################################################
# I2cBusProperties - simple encapsulation of all items
# required to control an I2C bus.
#
# Carl Jeske, July 2010
# Refactored by Robert Frazier, May 2011
##########################################################
class I2cBusProperties(object):
"""Encapsulates details of an I2C bus master in the form of a host device, a clock prescale value, and seven I2C master registers
Provide the ChipsBus instance to the device hosting your I2C core, a 16-bit clock prescaling
value for the Serial Clock Line (see I2C core docs for details), and the names of the seven
registers that define/control the bus (assuming these names are not the defaults specified
in the constructor below). The seven registers consist of the two clock pre-scaling
registers (PRElo, PREhi), and five bus master registers (CONTROL, TRANSMIT, RECEIVE,
COMMAND and STATUS).
Usage: You'll need to create an instance of this class to give to a concrete I2C bus instance, such
as OpenCoresI2cBus. This I2cBusProperties class is simply a container to hold the properties
that define the bus; a class such as OpenCoresI2cBus will make use of these properties.
Access the items stored by this class via these (deliberately compact) variable names:
chipsBus -- the ChipsBus device hosting the I2C core
preHiVal -- the top byte of the clock prescale value
preLoVal -- the bottom byte of the clock prescale value
preHiReg -- the register the top byte of the clk prescale value (preHiVal) gets written to
preLoReg -- the register the bottom byte of the clk prescale value (preLoVal) gets written to
ctrlReg -- the I2C Control register
txReg -- the I2C Transmit register
rxReg -- the I2C Receive register
cmdReg -- the I2C Command register
statusReg -- the I2C Status register
Compatibility Notes: The seven register names are the registers typically required to operate an
OpenCores or similar I2C Master (Lattice Semiconductor's I2C bus master works
the same way as the OpenCores one). This software is not compatible with your
I2C bus master if it doesn't use this register interface.
"""
def __init__(self,
chipsBusDevice,
clkPrescaleU16,
clkPrescaleLoByteReg = "i2c_pre_lo",
clkPrescaleHiByteReg = "i2c_pre_hi",
controlReg = "i2c_ctrl",
transmitReg = "i2c_tx",
receiveReg = "i2c_rx",
commandReg = "i2c_cmd",
statusReg = "i2c_status"):
"""Provide a host ChipsBus device that is controlling the I2C bus, and the names of five I2C control registers.
chipsBusDevice: Provide a ChipsBus instance to the device where the I2C bus is being
controlled. The address table for this device must contain the five registers
that control the bus, as declared next...
clkPrescaleU16: A 16-bit value used to prescale the Serial Clock Line based on the host
master-clock. This value gets split into two 8-bit values and ultimately will
get written to the two I2C clock-prescale registers as declared below. See
the OpenCores or Lattice Semiconductor I2C documentation for more details.
clkPrescaleLoByteReg: The register where the lower byte of the clock prescale value is set. The default
name for this register is "i2c_pre_lo".
clkPrescaleHiByteReg: The register where the higher byte of the clock prescale value is set. The default
name for this register is "i2c_pre_hi"
controlReg: The CONTROL register, used for enabling/disabling the I2C core, etc. This register is
usually read and write accessible. The default name for this register is "i2c_ctrl".
transmitReg: The TRANSMIT register, used for holding the data to be transmitted via I2C, etc. This
typically shares the same address as the RECEIVE register, but has write-only access. The default
name for this register is "i2c_tx".
receiveReg: The RECEIVE register - allows access to the byte received over the I2C bus. This
typically shares the same address as the TRANSMIT register, but has read-only access. The
default name for this register is "i2c_rx".
commandReg: The COMMAND register - stores the command for the next I2C operation. This typically
shares the same address as the STATUS register, but has write-only access. The default name for
this register is "i2c_cmd".
statusReg: The STATUS register - allows monitoring of the I2C operations. This typically shares
the same address as the COMMAND register, but has read-only access. The default name for this
register is "i2c_status".
"""
object.__init__(self)
self.chipsBus = chipsBusDevice
self.preHiVal = ((clkPrescaleU16 & 0xff00) >> 8)
self.preLoVal = (clkPrescaleU16 & 0xff)
# Check to see all the registers are in the address table
registers = [clkPrescaleLoByteReg, clkPrescaleHiByteReg, controlReg, transmitReg, receiveReg, commandReg, statusReg]
for reg in registers:
if not self.chipsBus.addrTable.checkItem(reg):
raise ChipsException("I2cBusProperties error: register '" + reg + "' is not present in the address table of the device hosting the I2C bus master!")
# Check that the registers we'll need to write to are indeed writable
writableRegisters = [clkPrescaleLoByteReg, clkPrescaleHiByteReg, controlReg, transmitReg, commandReg]
for wReg in writableRegisters:
if not self.chipsBus.addrTable.getItem(wReg).getWriteFlag():
raise ChipsException("I2cBusProperties error: register '" + wReg + "' does not have the necessary write permission!")
# Check that the registers we'll need to read from are indeed readable
readableRegisters = [clkPrescaleLoByteReg, clkPrescaleHiByteReg, controlReg, receiveReg, statusReg]
for rReg in readableRegisters:
if not self.chipsBus.addrTable.getItem(rReg).getReadFlag():
raise ChipsException("I2cBusProperties error: register '" + rReg + "' does not have the necessary read permission!")
# Store the various register name strings
self.preHiReg = clkPrescaleHiByteReg
self.preLoReg = clkPrescaleLoByteReg
self.ctrlReg = controlReg
self.txReg = transmitReg
self.rxReg = receiveReg
self.cmdReg = commandReg
self.statusReg = statusReg
# -*- coding: utf-8 -*-
import uhal
from I2CuHal import I2CCore
import StringIO
class PCA9539PW:
#Class to configure the expander modules
def __init__(self, i2c, slaveaddr=0x74):
self.i2c = i2c
self.slaveaddr = slaveaddr
def writeReg(self, regN, regContent, verbose=False):
#Basic functionality to write to register.
if (regN < 0) | (regN > 7):
print "PCA9539PW - ERROR: register number should be in range [0:7]"
return
regContent= regContent & 0xFF
mystop=True
cmd= [regN, regContent]
self.i2c.write( self.slaveaddr, cmd, mystop)
def readReg(self, regN, nwords, verbose=False):
#Basic functionality to read from register.
if (regN < 0) | (regN > 7):
print "PCA9539PW - ERROR: register number should be in range [0:7]"
return
mystop=False
self.i2c.write( self.slaveaddr, [regN], mystop)
res= self.i2c.read( self.slaveaddr, nwords)
return res
def setInvertReg(self, regN, polarity= 0x00):
#Set the content of register 4 or 5 which determine the polarity of the
#ports (0= normal, 1= inverted).
if (regN < 0) | (regN > 1):
print "PCA9539PW - ERROR: regN should be 0 or 1"
return
polarity = polarity & 0xFF
self.writeReg(regN+4, polarity)
def getInvertReg(self, regN):
#Read the content of register 4 or 5 which determine the polarity of the
#ports (0= normal, 1= inverted).
if (regN < 0) | (regN > 1):
print "PCA9539PW - ERROR: regN should be 0 or 1"
return
res= self.readReg(regN+4, 1)
return res
def setIOReg(self, regN, direction= 0xFF):
#Set the content of register 6 or 7 which determine the direction of the
#ports (0= output, 1= input).
if (regN < 0) | (regN > 1):
print "PCA9539PW - ERROR: regN should be 0 or 1"
return
direction = direction & 0xFF
self.writeReg(regN+6, direction)
def getIOReg(self, regN):
#Read the content of register 6 or 7 which determine the polarity of the
#ports (0= normal, 1= inverted).
if (regN < 0) | (regN > 1):
print "PCA9539PW - ERROR: regN should be 0 or 1"
return
res= self.readReg(regN+6, 1)
return res
def getInputs(self, bank):
#Read the incoming values of the pins for one of the two 8-bit banks.
if (bank < 0) | (bank > 1):
print "PCA9539PW - ERROR: bank should be 0 or 1"
return
res= self.readReg(bank, 1)
return res
def setOutputs(self, bank, values= 0x00):
#Set the content of the output flip-flops.
if (bank < 0) | (bank > 1):
print "PCA9539PW - ERROR: bank should be 0 or 1"
return
values = values & 0xFF
self.writeReg(bank+2, values)
# Created on Sep 10, 2012
# @author: Kristian Harder, based on code by Carl Jeske
from I2cBusProperties import I2cBusProperties
from ChipsBus import ChipsBus
from ChipsLog import chipsLog
from ChipsException import ChipsException
class RawI2cAccess:
def __init__(self, i2cBusProps, slaveAddr):
# For performing read/writes over an OpenCores-compatible I2C bus master
#
# An instance of this class is required to communicate with each
# I2C slave on the I2C bus.
#
# i2cBusProps: an instance of the class I2cBusProperties that contains
# the relevant ChipsBus host and the I2C bus-master registers (if
# they differ from the defaults specified by the I2cBusProperties
# class).
#
#slaveAddr: The address of the I2C slave you wish to communicate with.
#
self._i2cProps = i2cBusProps # The I2C Bus Properties
self._slaveAddr = 0x7f & slaveAddr # 7-bit slave address
def resetI2cBus(self):
# Resets the I2C bus
#
# This function does the following:
# 1) Disables the I2C core
# 2) Sets the clock prescale registers
# 3) Enables the I2C core
# 4) Sets all writable bus-master registers to default values
try:
self._chipsBus().queueWrite(self._i2cProps.ctrlReg, 0x00)
#self._chipsBus().getNode(self._i2cProps.ctrlReg).write(0)
self._chipsBus().queueWrite(self._i2cProps.preHiReg,
self._i2cProps.preHiVal)
self._chipsBus().queueWrite(self._i2cProps.preLoReg,
self._i2cProps.preLoVal)
self._chipsBus().queueWrite(self._i2cProps.ctrlReg, 0x80)
self._chipsBus().queueWrite(self._i2cProps.txReg, 0x00)
self._chipsBus().queueWrite(self._i2cProps.cmdReg, 0x00)
self._chipsBus().queueRun()
except ChipsException, err:
raise ChipsException("I2C reset error:\n\t" + str(err))
def read(self, numBytes):
# Performs an I2C read. Returns the 8-bit read result(s).
#
# numBytes: number of bytes expected as response
#
try:
result = self._privateRead(numBytes)
except ChipsException, err:
raise ChipsException("I2C read error:\n\t" + str(err))
return result
def write(self, listDataU8):
# Performs an 8-bit I2C write.
#
# listDataU8: The 8-bit data values to be written.
#
try:
self._privateWrite(listDataU8)
except ChipsException, err:
raise ChipsException("I2C write error:\n\t" + str(err))
return
def _chipsBus(self):
# Returns the instance of the ChipsBus device that's hosting
# the I2C bus master
return self._i2cProps.chipsBus
def _privateRead(self, numBytes):
# I2C read implementation.
#
# Fast I2C read implementation,
# i.e. done with the fewest packets possible.
# transmit reg definitions
# bits 7-1: 7-bit slave address during address transfer
# or first 7 bits of byte during data transfer
# bit 0: RW flag during address transfer or LSB during data transfer.
# '1' = reading from slave
# '0' = writing to slave
# command reg definitions
# bit 7: Generate start condition
# bit 6: Generate stop condition
# bit 5: Read from slave
# bit 4: Write to slave
# bit 3: 0 when acknowledgement is received
# bit 2:1: Reserved
# bit 0: Interrupt acknowledge. When set, clears a pending interrupt
# Reset bus before beginning
self.resetI2cBus()
# Set slave address in bits 7:1, and set bit 0 to zero
# (i.e. we're writing an address to the bus)
self._chipsBus().queueWrite(self._i2cProps.txReg,
(self._slaveAddr << 1) | 0x01)
# Set start and write bit in command reg
self._chipsBus().queueWrite(self._i2cProps.cmdReg, 0x90)
# Run the queue
self._chipsBus().queueRun()
# Wait for transaction to finish.
self._i2cWaitUntilFinished()
result=[]
for ibyte in range(numBytes):
if ibyte==numBytes-1:
stop_bit=0x40
ack_bit=0x08
else:
stop_bit=0
ack_bit=0
pass
# Set read bit, acknowledge and stop bit in command reg
self._chipsBus().write(self._i2cProps.cmdReg, 0x20+ack_bit+stop_bit)
# Wait for transaction to finish.
# Don't expect an ACK, do expect bus free at finish.
if stop_bit:
self._i2cWaitUntilFinished(requireAcknowledgement = False,
requireBusIdleAtEnd = True)
else:
self._i2cWaitUntilFinished(requireAcknowledgement = False,
requireBusIdleAtEnd = False)
pass
result.append(self._chipsBus().read(self._i2cProps.rxReg))
return result
def _privateWrite(self, listDataU8):
# I2C write implementation.
#
# Fast I2C write implementation,
# i.e. done with the fewest packets possible.
# transmit reg definitions
# bits 7-1: 7-bit slave address during address transfer
# or first 7 bits of byte during data transfer
# bit 0: RW flag during address transfer or LSB during data transfer.
# '1' = reading from slave
# '0' = writing to slave
# command reg definitions
# bit 7: Generate start condition
# bit 6: Generate stop condition
# bit 5: Read from slave
# bit 4: Write to slave
# bit 3: 0 when acknowledgement is received
# bit 2:1: Reserved
# bit 0: Interrupt acknowledge. When set, clears a pending interrupt
# Reset bus before beginning
self.resetI2cBus()
# Set slave address in bits 7:1, and set bit 0 to zero (i.e. "write mode")
self._chipsBus().queueWrite(self._i2cProps.txReg,
(self._slaveAddr << 1) & 0xfe)
# Set start and write bit in command reg
self._chipsBus().queueWrite(self._i2cProps.cmdReg, 0x90)
# Run the queue
self._chipsBus().queueRun()
# Wait for transaction to finish.
self._i2cWaitUntilFinished()
for ibyte in range(len(listDataU8)):
dataU8 = listDataU8[ibyte]
if ibyte==len(listDataU8)-1:
stop_bit=0x40
else:
stop_bit=0x00
pass
# Set data to be written in transmit reg
self._chipsBus().queueWrite(self._i2cProps.txReg, (dataU8 & 0xff))
# Set write and stop bit in command reg
self._chipsBus().queueWrite(self._i2cProps.cmdReg, 0x10+stop_bit)
# Run the queue
self._chipsBus().queueRun()
# Wait for transaction to finish.
# Do expect an ACK and do expect bus to be free at finish
if stop_bit:
self._i2cWaitUntilFinished(requireAcknowledgement = True,
requireBusIdleAtEnd = True)
else:
self._i2cWaitUntilFinished(requireAcknowledgement = True,
requireBusIdleAtEnd = False)
pass
pass
return
def _i2cWaitUntilFinished(self, requireAcknowledgement = True,
requireBusIdleAtEnd = False):
# Ensures the current bus transaction has finished successfully
# before allowing further I2C bus transactions
# This method monitors the status register
# and will not allow execution to continue until the
# I2C bus has completed properly. It will throw an exception
# if it picks up bus problems or a bus timeout occurs.
maxRetry = 20
attempt = 1
while attempt <= maxRetry:
# Get the status
i2c_status = self._chipsBus().read(self._i2cProps.statusReg)
receivedAcknowledge = not bool(i2c_status & 0x80)
busy = bool(i2c_status & 0x40)
arbitrationLost = bool(i2c_status & 0x20)
transferInProgress = bool(i2c_status & 0x02)
interruptFlag = bool(i2c_status & 0x01)
if arbitrationLost: # This is an instant error at any time
raise ChipsException("I2C error: Arbitration lost!")
if not transferInProgress:
break # The transfer looks to have completed successfully, pending further checks
attempt += 1
# At this point, we've either had too many retries, or the
# Transfer in Progress (TIP) bit went low. If the TIP bit
# did go low, then we do a couple of other checks to see if
# the bus operated as expected:
if attempt > maxRetry:
raise ChipsException("I2C error: Transaction timeout - the 'Transfer in Progress' bit remained high for too long!")
if requireAcknowledgement and not receivedAcknowledge:
raise ChipsException("I2C error: No acknowledge received!")
if requireBusIdleAtEnd and busy:
raise ChipsException("I2C error: Transfer finished but bus still busy!")
This diff is collapsed.
<?xml version="1.0" encoding="ISO-8859-1"?>
<node id="TLU">
<!-- Registers for the DUTs. These should be correct -->
<node id="DUTInterfaces" address="0x1000" description="DUT Interfaces control registers">
<node id="DutMaskW" address="0x0" permission="w" description="" />
<node id="IgnoreDUTBusyW" address="0x1" permission="w" description="" />
<node id="IgnoreShutterVetoW" address="0x2" permission="w" description="" />
<node id="DUTInterfaceModeW" address="0x3" permission="w" description="" />
<node id="DUTInterfaceModeModifierW" address="0x4" permission="w" description="" />
<node id="DUTInterfaceModeR" address="0xB" permission="r" description="" />
<node id="DUTInterfaceModeModifierR" address="0xC" permission="r" description="" />
<node id="DutMaskR" address="0x8" permission="r" description="" />
<node id="IgnoreDUTBusyR" address="0x9" permission="r" description="" />
<node id="IgnoreShutterVetoR" address="0xA" permission="r" description="" />
</node>
<node id="Shutter" address="0x2000" description="Shutter/T0 control">
<node id="ShutterStateW" address="0x0" permission="w" description=""/>
<node id="PulseT0" address="0x1" permission="w" description=""/>
</node>
<!-- I2C registers. Tested ok.-->
<node id="i2c_master" address="0x3000" description="I2C Master interface">
<node id="i2c_pre_lo" address="0x0" mask="0x000000ff" permission="rw" description="" />
<node id="i2c_pre_hi" address="0x1" mask="0x000000ff" permission="rw" description="" />
<node id="i2c_ctrl" address="0x2" mask="0x000000ff" permission="rw" description="" />
<node id="i2c_rxtx" address="0x3" mask="0x000000ff" permission="rw" description="" />
<node id="i2c_cmdstatus" address="0x4" mask="0x000000ff" permission="rw" description="" />
</node>
<!-- Not sure about the FillLevelFlags register -->
<node id="eventBuffer" address="0x4000" description="Event buffer">
<node id="EventFifoData" address="0x0" mode="non-incremental" size="32000" permission="r" description="" />
<node id="EventFifoFillLevel" address="0x1" permission="r" description="" />
<node id="EventFifoCSR" address="0x2" permission="rw" description="" />
<node id="EventFifoFillLevelFlags" address="0x3" permission="r" description="" />
</node>
<!-- Event formatter registers. Should be ok -->
<node id="Event_Formatter" address="0x5000" description="Event formatter configuration">
<node id="Enable_Record_Data" address="0x0" permission="rw" description="" />
<node id="ResetTimestampW" address="0x1" permission="w" description="" />
<node id="CurrentTimestampLR" address="0x2" permission="r" description="" />
<node id="CurrentTimestampHR" address="0x3" permission="r" description="" />
</node>
<!-- This needs checking. The counters work, not sure about the reset -->
<node id="triggerInputs" address="0x6000" description="Inputs configuration">
<node id="SerdesRstW" address="0x0" permission="w" description="" />
<node id="SerdesRstR" address="0x8" permission="r" description="" />
<node id="ThrCount0R" address="0x9" permission="r" description="" />
<node id="ThrCount1R" address="0xa" permission="r" description="" />
<node id="ThrCount2R" address="0xb" permission="r" description="" />
<node id="ThrCount3R" address="0xc" permission="r" description="" />
<node id="ThrCount4R" address="0xd" permission="r" description="" />
<node id="ThrCount5R" address="0xe" permission="r" description="" />
</node>
<!-- Checked. Seems ok now, except for the TriggerVeto that do nothing.-->
<node id="triggerLogic" address="0x7000" description="Trigger logic configuration">
<node id="PostVetoTriggersR" address="0x10" permission="r" description="" />
<node id="PreVetoTriggersR" address="0x11" permission="r" description="" />
<node id="InternalTriggerIntervalW" address="0x2" permission="w" description="" />
<node id="InternalTriggerIntervalR" address="0x12" permission="r" description="" />
<!--<node id="TriggerPatternW" address="0x3" permission="w" description="" />-->
<!--<node id="TriggerPatternR" address="0x13" permission="r" description="" />-->
<node id="TriggerVetoW" address="0x4" permission="w" description="" />
<node id="TriggerVetoR" address="0x14" permission="r" description="" /><!--Wait, this does nothing at the moment...-->
<node id="ExternalTriggerVetoR" address="0x15" permission="r" description="" />
<node id="PulseStretchW" address="0x6" permission="w" description="" />
<node id="PulseStretchR" address="0x16" permission="r" description="" />
<node id="PulseDelayW" address="0x7" permission="w" description="" />
<node id="PulseDelayR" address="0x17" permission="r" description="" />
<node id="TriggerHoldOffW" address="0x8" permission="W" description="" /><!--Wait, this does nothing at the moment...-->
<node id="TriggerHoldOffR" address="0x18" permission="r" description="" /><!--Wait, this does nothing at the moment...-->
<node id="AuxTriggerCountR" address="0x19" permission="r" description="" />
<node id="TriggerPattern_lowW" address="0xA" permission="w" description="" />
<node id="TriggerPattern_lowR" address="0x1A" permission="r" description="" />
<node id="TriggerPattern_highW" address="0xB" permission="w" description="" />
<node id="TriggerPattern_highR" address="0x1B" permission="r" description="" />
<!--<node id="PulseStretchW" address="0x6" permission="w" description="" /> OLD REGISTER MAP. WAS BUGGED-->
<!--<node id="PulseStretchR" address="0x16" permission="r" description="" /> OLD REGISTER MAP. WAS BUGGED-->
<!--
<node id="ResetCountersW" address="0x6" permission="w" description="" />
<node id="PulseStretchR" address="0x17" permission="r" description="" />
<node id="PulseStretchW" address="0x7" permission="w" description="" />
<node id="TriggerHoldOffR" address="0x18" permission="r" description="" />
<node id="TriggerHoldOffW" address="0x8" permission="W" description="" />
<node id="AuxTriggerCountR" address="0x19" permission="r" description="" />
-->
</node>
<node id="logic_clocks" address="0x8000" description="Clocks configuration">
<node id="LogicClocksCSR" address="0x0" permission="rw" description="" />
<node id="LogicRst" address="0x1" permission="w" description="" />
</node>
<node id="version" address="0x1" description="firmware version" permission="r">
</node>
<!--
PulseStretchW 0x00000066 0xffffffff 0 1
PulseDelayW 0x00000067 0xffffffff 0 1
PulseDelayR 0x00000077 0xffffffff 1 0
-->
</node>
<?xml version="1.0" encoding="UTF-8"?>
<connections>
<connection id="tlu" uri="ipbusudp-2.0://192.168.200.31:50001"
address_table="file://./TLUaddrmap.xml" />
</connections>
*RegName RegAddr RegMask R W
*-------------------------------------------------------------
FirmwareId 0x00000000 0xffffffff 1 0
*
* DUT interfaces base = 0x020
DUTMaskW 0x00000020 0xffffffff 0 1
IgnoreDUTBusyW 0x00000021 0xffffffff 0 1
IgnoreShutterVetoW 0x00000022 0xffffffff 0 1
DUTInterfaceModeW 0x00000023 0xffffffff 0 1
DUTInterfaceModeModifierW 0x00000024 0xffffffff 0 1
DUTMaskR 0x00000028 0xffffffff 1 0
IgnoreDUTBusyR 0x00000029 0xffffffff 1 0
IgnoreShutterVetoR 0x0000002A 0xffffffff 1 0
DUTInterfaceModeR 0x0000002B 0xffffffff 1 0
DUTInterfaceModeModifierR 0x0000002C 0xffffffff 1 0
*
* trigger inputs = 0x040
SerdesRstW 0x00000040 0xffffffff 0 1
SerdesRstR 0x00000048 0xffffffff 1 0
ThrCount0R 0x00000049 0xffffffff 1 0
ThrCount1R 0x0000004a 0xffffffff 1 0
ThrCount2R 0x0000004b 0xffffffff 1 0
ThrCount3R 0x0000004c 0xffffffff 1 0
*
* trigger logic = 0x060 **Note the different read and write directions
InternalTriggerIntervalW 0x00000062 0xffffffff 0 1
TriggerPatternW 0x00000063 0xffffffff 0 1
TriggerVetoW 0x00000064 0xffffffff 0 1
PulseStretchW 0x00000066 0xffffffff 0 1
PulseDelayW 0x00000067 0xffffffff 0 1
TriggerHoldOffW 0x00000068 0xffffffff 0 1
PostVetoTriggersR 0x00000070 0xffffffff 1 0
PreVetoTriggersR 0x00000071 0xffffffff 1 0
InternalTriggerIntervalR 0x00000072 0xffffffff 1 0
TriggerPatternR 0x00000073 0xffffffff 1 0
TriggerVetoR 0x00000074 0xffffffff 1 0
ExternalTriggerVetoR 0x00000075 0xffffffff 1 0
PulseStretchR 0x00000076 0xffffffff 1 0
PulseDelayR 0x00000077 0xffffffff 1 0
TriggerHoldOffR 0x00000078 0xffffffff 1 0
AuxTriggerCountR 0x00000079 0xffffffff 1 0
*
* event buffer = 0x080
EventFifoData 0x00000080 0xffffffff 1 0
EventFifoFillLevel 0x00000081 0xffffffff 1 0
EventFifoCSR 0x00000082 0xffffffff 1 1
EventFifoFillLevelFlags 0x00000083 0xffffffff 1 0
*
* logic clocks = 0x0A0
LogicClocksCSR 0x000000A0 0xffffffff 1 1
LogicRst 0x000000A1 0xffffffff 0 1
*
* I2C = 0x0C0
i2c_pre_lo 0x000000C0 0x000000ff 1 1
i2c_pre_hi 0x000000C1 0x000000ff 1 1
i2c_ctrl 0x000000C2 0x000000ff 1 1
i2c_tx 0x000000C3 0x000000ff 0 1
i2c_rx 0x000000C3 0x000000ff 1 0
i2c_cmd 0x000000C4 0x000000ff 0 1
i2c_status 0x000000C4 0x000000ff 1 0
*
* Event formatter = 0x140
Enable_Record_Data 0x00000140 0xffffffff 1 1
ResetTimestampW 0x00000141 0xffffffff 0 1
CurrentTimestampLR 0x00000142 0xffffffff 1 0
CurrentTimestampHR 0x00000143 0xffffffff 1 0
*
* Shutter/T0 control = 0x160
ShutterStateW 0x00000160 0xffffffff 0 1
PulseT0 0x00000161 0xffffffff 0 1
#
# Function to initialize TLU
#
# David Cussans, October 2015
#
# Nasty hack - use both PyChips and uHAL ( for block read ... )
from PyChipsUser import *
from FmcTluI2c import *
import uhal
import sys
import time
def startTLU( uhalDevice , pychipsBoard , writeTimestamps):
print "RESETTING FIFO"
pychipsBoard.write("EventFifoCSR",0x2)
eventFifoFillLevel = pychipsBoard.read("EventFifoFillLevel")
print "FIFO FILL LEVEL AFTER RESET= " , eventFifoFillLevel
if writeTimestamps:
print "ENABLING DATA RECORDING"
pychipsBoard.write("Enable_Record_Data",1)
else:
print "Disabling data recording"
pychipsBoard.write("Enable_Record_Data",0)
print "Pulsing T0"
pychipsBoard.write("PulseT0",1)
print "Turning off software trigger veto"
pychipsBoard.write("TriggerVetoW",0)
print "TLU is running"
def stopTLU( uhalDevice , pychipsBoard ):
print "Turning on software trigger veto"
pychipsBoard.write("TriggerVetoW",1)
print "TLU triggers are stopped"
def initTLU( uhalDevice , pychipsBoard , listenForTelescopeShutter , pulseDelay , pulseStretch , triggerPattern , DUTMask , ignoreDUTBusy , triggerInterval , thresholdVoltage ):
print "SETTING UP AIDA TLU"
fwVersion = uhalDevice.getNode("version").read()
uhalDevice.dispatch()
print "\tVersion (uHAL)= " , hex(fwVersion)
print "\tTurning on software trigger veto"
pychipsBoard.write("TriggerVetoW",1)
# Check the bus for I2C devices
pychipsBoardi2c = FmcTluI2c(pychipsBoard)
print "\tScanning I2C bus:"
scanResults = pychipsBoardi2c.i2c_scan()
#print scanResults
print '\t', ', '.join(scanResults), '\n'
boardId = pychipsBoardi2c.get_serial_number()
print "\tFMC-TLU serial number= " , boardId
resetClocks = 0
resetSerdes = 0
# set DACs to -200mV
print "\tSETTING ALL DAC THRESHOLDS TO" , thresholdVoltage , "V"
pychipsBoardi2c.set_threshold_voltage(7, thresholdVoltage)
clockStatus = pychipsBoard.read("LogicClocksCSR")
print "\tCLOCK STATUS (should be 3 if all clocks locked)= " , hex(clockStatus)
assert ( clockStatus == 3 ) , "Clocks in TLU FPGA are not locked. No point in continuing. Re-prgramme or power cycle board"
if resetClocks:
print "Resetting clocks"
pychipsBoard.write("LogicRst", 1 )
clockStatus = pychipsBoard.read("LogicClocksCSR")
print "Clock status after reset = " , hex(clockStatus)
inputStatus = pychipsBoard.read("SerdesRstR")
print "Input status = " , hex(inputStatus)
if resetSerdes:
pychipsBoard.write("SerdesRstW", 0x00000003 )
inputStatus = pychipsBoard.read("SerdesRstR")
print "Input status during reset = " , hex(inputStatus)
pychipsBoard.write("SerdesRstW", 0x00000000 )
inputStatus = pychipsBoard.read("SerdesRstR")
print "Input status after reset = " , hex(inputStatus)
pychipsBoard.write("SerdesRstW", 0x00000004 )
inputStatus = pychipsBoard.read("SerdesRstR")
print "Input status during calibration = " , hex(inputStatus)
pychipsBoard.write("SerdesRstW", 0x00000000 )
inputStatus = pychipsBoard.read("SerdesRstR")
print "Input status after calibration = " , hex(inputStatus)
inputStatus = pychipsBoard.read("SerdesRstR")
print "\tINPUT STATUS= " , hex(inputStatus)
count0 = pychipsBoard.read("ThrCount0R")
print "\t Count 0= " , count0
count1 = pychipsBoard.read("ThrCount1R")
print "\t Count 1= " , count1
count2 = pychipsBoard.read("ThrCount2R")
print "\t Count 2= " , count2
count3 = pychipsBoard.read("ThrCount3R")
print "\t Count 3= " , count3
# Stop internal triggers until setup complete
pychipsBoard.write("InternalTriggerIntervalW",0)
print "\tSETTING INPUT COINCIDENCE WINDOW TO",pulseStretch,"[Units= 160MHz clock cycles, Four 5-bit values (one per input) packed in to 32-bit word]"
pychipsBoard.write("PulseStretchW",int(pulseStretch))
pulseStretchR = pychipsBoard.read("PulseStretchR")
print "\t Pulse stretch read back as:", hex(pulseStretchR)
# assert (int(pulseStretch) == pulseStretchR) , "Pulse stretch read-back doesn't equal written value"
print "\tSETTING INPUT TRIGGER DELAY TO",pulseDelay , "[Units= 160MHz clock cycles, Four 5-bit values (one per input) packed in to 32-bit word]"
pychipsBoard.write("PulseDelayW",int(pulseDelay))
pulseDelayR = pychipsBoard.read("PulseDelayR")
print "\t Pulse delay read back as:", hex(pulseDelayR)
print "\tSETTING TRIGGER PATTERN (for external triggers) TO 0x%08X. Two 16-bit patterns packed into 32 bit word " %(triggerPattern)
pychipsBoard.write("TriggerPatternW",int(triggerPattern))
triggerPatternR = pychipsBoard.read("TriggerPatternR")
print "\t Trigger pattern read back as: 0x%08X " % (triggerPatternR)
print "\tENABLING DUT(s): Mask= " , hex(DUTMask)
pychipsBoard.write("DUTMaskW",int(DUTMask))
DUTMaskR = pychipsBoard.read("DUTMaskR")
print "\t DUTMask read back as:" , hex(DUTMaskR)
print "\tSETTING ALL DUTs IN AIDA MODE"
pychipsBoard.write("DUTInterfaceModeW", 0xFF)
DUTInterfaceModeR = pychipsBoard.read("DUTInterfaceModeR")
print "\t DUT mode read back as:" , DUTInterfaceModeR
print "\tSET DUT MODE MODIFIER"
pychipsBoard.write("DUTInterfaceModeModifierW", 0xFF)
DUTInterfaceModeModifierR = pychipsBoard.read("DUTInterfaceModeModifierR")
print "\t DUT mode modifier read back as:" , DUTInterfaceModeModifierR
if listenForTelescopeShutter:
print "\tSET IgnoreShutterVetoW TO LISTEN FOR VETO FROM SHUTTER"
pychipsBoard.write("IgnoreShutterVetoW",0)
else:
print "\tSET IgnoreShutterVetoW TO IGNORE VETO FROM SHUTTER"
pychipsBoard.write("IgnoreShutterVetoW",1)
IgnoreShutterVeto = pychipsBoard.read("IgnoreShutterVetoR")
print "\t IgnoreShutterVeto read back as:" , IgnoreShutterVeto
print "\tSETTING IGNORE VETO BY DUT BUSY MASK TO" , hex(ignoreDUTBusy)
pychipsBoard.write("IgnoreDUTBusyW",int(ignoreDUTBusy))
IgnoreDUTBusy = pychipsBoard.read("IgnoreDUTBusyR")
print "\t IgnoreDUTBusy read back as:" , hex(IgnoreDUTBusy)
#print "Enabling handshake: No-handshake"
#board.write("HandshakeTypeW",1)
print "\tSETTING INTERNAL TRIGGER INTERVAL TO" , triggerInterval , "(zero= no internal triggers)"
if triggerInterval == 0:
internalTriggerFreq = 0
else:
internalTriggerFreq = 160000.0/triggerInterval
print "\tINTERNAL TRIGGER FREQUENCY= " , internalTriggerFreq , " kHz"
pychipsBoard.write("InternalTriggerIntervalW",triggerInterval) #0->Internal pulse generator disabled. Any other value will generate pulses with a frequency of n*6.25ns
trigIntervalR = pychipsBoard.read("InternalTriggerIntervalR")
print "\t Trigger interval read back as:", trigIntervalR
print "AIDA TLU SETUP COMPLETED"
This diff is collapsed.
import time
import uhal
from I2CuHal import I2CCore
import StringIO
import csv
class si5345:
#Class to configure the Si5344 clock generator
def __init__(self, i2c, slaveaddr=0x68):
self.i2c = i2c
self.slaveaddr = slaveaddr
#self.configList=
#def writeReg(self, address, data):
def readRegister(self, myaddr, nwords, verbose= False):
### Read a specific register on the Si5344 chip. There is not check on the validity of the address but
### the code sets the correct page before reading.
#First make sure we are on the correct page
currentPg= self.getPage()
requirePg= (myaddr & 0xFF00) >> 8
if verbose:
print "REG", hex(myaddr), "CURR PG" , hex(currentPg[0]), "REQ PG", hex(requirePg)
if currentPg[0] != requirePg:
self.setPage(requirePg)
#Now read from register.
addr=[]
addr.append(myaddr)
mystop=False
self.i2c.write( self.slaveaddr, addr, mystop)
# time.sleep(0.1)
res= self.i2c.read( self.slaveaddr, nwords)
return res
def writeRegister(self, myaddr, data, verbose=False):
### Write a specific register on the Si5344 chip. There is not check on the validity of the address but
### the code sets the correct page before reading.
### myaddr is an int
### data is a list of ints
#First make sure we are on the correct page
myaddr= myaddr & 0xFFFF
currentPg= self.getPage()
requirePg= (myaddr & 0xFF00) >> 8
#print "REG", hex(myaddr), "CURR PG" , currentPg, "REQ PG", hex(requirePg)
if currentPg[0] != requirePg:
self.setPage(requirePg)
#Now write to register.
data.insert(0, myaddr)
if verbose:
print " Writing: "
result="\t "
for iaddr in data:
result+="%#02x "%(iaddr)
print result
self.i2c.write( self.slaveaddr, data)
#time.sleep(0.01)
def setPage(self, page, verbose=False):
#Configure the chip to perform operations on the specified address page.
mystop=True
myaddr= [0x01, page]
self.i2c.write( self.slaveaddr, myaddr, mystop)
#time.sleep(0.01)
if verbose:
print " Si5345 Set Reg Page:", page
def getPage(self, verbose=False):
#Read the current address page
mystop=False
myaddr= [0x01]
self.i2c.write( self.slaveaddr, myaddr, mystop)
rPage= self.i2c.read( self.slaveaddr, 1)
#time.sleep(0.1)
if verbose:
print "\tPage read:", rPage
return rPage
def getDeviceVersion(self):
#Read registers containing chip information
mystop=False
nwords=2
myaddr= [0x02 ]#0xfa
self.setPage(0)
self.i2c.write( self.slaveaddr, myaddr, mystop)
#time.sleep(0.1)
res= self.i2c.read( self.slaveaddr, nwords)
print " Si5345 EPROM: "
result="\t"
for iaddr in reversed(res):
result+="%#02x "%(iaddr)
print result
return res
def parse_clk(self, filename, verbose= False):
#Parse the configuration file produced by Clockbuilder Pro (Silicon Labs)
deletedcomments=""""""
if verbose:
print "\tParsing file", filename
with open(filename, 'rb') as configfile:
for i, line in enumerate(configfile):
if not line.startswith('#') :
if not line.startswith('Address'):
deletedcomments+=line
csvfile = StringIO.StringIO(deletedcomments)
cvr= csv.reader(csvfile, delimiter=',', quotechar='|')
#print "\tN elements parser:", sum(1 for row in cvr)
#return [addr_list,data_list]
# for item in cvr:
# print "rere"
# regAddr= int(item[0], 16)
# regData[0]= int(item[1], 16)
# print "\t ", hex(regAddr), hex(regData[0])
#self.configList= cvr
regSettingList= list(cvr)
if verbose:
print "\t ", len(regSettingList), "elements"
return regSettingList
def writeConfiguration(self, regSettingList):
print " Si5345 Writing configuration:"
#regSettingList= list(regSettingCsv)
counter=0
for item in regSettingList:
regAddr= int(item[0], 16)
regData=[0]
regData[0]= int(item[1], 16)
print "\t", counter, "Reg:", hex(regAddr), "Data:", regData
counter += 1
self.writeRegister(regAddr, regData, False)
def checkDesignID(self):
regAddr= 0x026B
res= self.readRegister(regAddr, 8)
result= " Si5345 design Id:\n\t"
for iaddr in res:
result+=chr(iaddr)
print result
#!/bin/bash
echo "=========================="
CURRENT_DIR=${0%/*}
echo "CURRENT DIRECTORY: " $CURRENT_DIR
echo "============"
echo "SETTING PATHS"
export PYTHONPATH=$CURRENT_DIR/../../../../Python_Scripts/PyChips_1_5_0_pre2A/src:$PYTHONPATH
export PYTHONPATH=~/Python_Scripts/PyChips_1_5_0_pre2A/src:$PYTHONPATH
echo "PYTHON PATH= " $PYTHONPATH
export LD_LIBRARY_PATH=/opt/cactus/lib:$LD_LIBRARY_PATH
echo "LD_LIBRARY_PATH= " $LD_LIBRARY_PATH
export PATH=/usr/bin/:/opt/cactus/bin:$PATH
echo "PATH= " $PATH
cd $CURRENT_DIR
echo "============"
echo "STARTING PYTHON SCRIPT FOR TLU"
#python $CURRENT_DIR/startTLU_v8.py $@
python startTLU_v8.py $@
#python testTLU_script.py
#
# Script to setup AIDA TLU for TPix3 telescope <--> TORCH synchronization
#
# David Cussans, December 2012
#
# Nasty hack - use both PyChips and uHAL ( for block read ... )
from PyChipsUser import *
from FmcTluI2c import *
import uhal
import sys
import time
from datetime import datetime
from optparse import OptionParser
# For single character non-blocking input:
import select
import tty
import termios
from initTLU import *
def isData():
return select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], [])
now = datetime.now().strftime('%Y-%m-%dT%H_%M_%S')
default_filename = 'tluData_' + now + '.root'
parser = OptionParser()
parser.add_option('-r','--rootFname',dest='rootFname',
default=default_filename,help='Path of output file')
parser.add_option('-o','--writeTimestamps',dest='writeTimestamps',
default="True",help='Set True to write timestamps to ROOT file')
parser.add_option('-p','--printTimestamps',dest='printTimestamps',
default="True",help='Set True to print timestamps to screen (nothing printed unless also output to file) ')
parser.add_option('-s','--listenForTelescopeShutter',dest='listenForTelescopeShutter',
default=False,help='Set True to veto triggers when shutter goes high')
parser.add_option('-d','--pulseDelay',dest='pulseDelay', type=int,
default=0x00,help='Delay added to input triggers. Four 5-bit numbers packed into 32-bt word, Units of 6.125ns')
parser.add_option('-w','--pulseStretch',dest='pulseStretch',type=int,
default=0x00,help='Width added to input triggers. Four 5-bit numbers packed into 32-bt word. Units of 6.125ns')
parser.add_option('-t','--triggerPattern',dest='triggerPattern',type=int,
default=0xFFFEFFFE,help='Pattern match to generate trigger. Two 16-bit words packed into 32-bit word.')
parser.add_option('-m','--DUTMask',dest='DUTMask',type=int,
default=0x01,help='Three-bit mask selecting which DUTs are active.')
parser.add_option('-y','--ignoreDUTBusy',dest='ignoreDUTBusy',type=int,
default=0x0F,help='Three-bit mask selecting which DUTs can veto triggers by setting BUSY high. Low = can veto, high = ignore busy.')
parser.add_option('-i','--triggerInterval',dest='triggerInterval',type=int,
default=0,help='Interval between internal trigers ( in units of 6.125ns ). Set to zero to turn off internal triggers')
parser.add_option('-v','--thresholdVoltage',dest='thresholdVoltage',type=float,
default=-0.2,help='Threshold voltage for TLU inputs ( units of volts)')
(options, args) = parser.parse_args(sys.argv[1:])
from ROOT import TFile, TTree
from ROOT import gROOT
print "SETTING UP AIDA TLU TO SUPPLY CLOCK AND TRIGGER TO TORCH READOUT\n"
# Point to board in uHAL
manager = uhal.ConnectionManager("file://./connection.xml")
hw = manager.getDevice("minitlu")
device_id = hw.id()
# Point to TLU in Pychips
bAddrTab = AddressTable("./aida_mini_tlu_addr_map.txt")
# Assume DIP-switch controlled address. Switches at 2
board = ChipsBusUdp(bAddrTab,"192.168.200.32",50001)
# Open Root file
print "OPENING ROOT FILE:", options.rootFname
f = TFile( options.rootFname, 'RECREATE' )
# Create a root "tree"
tree = TTree( 'T', 'TLU Data' )
highWord =0
lowWord =0
evtNumber=0
timeStamp=0
evtType=0
trigsFired=0
bufPos = 0
# Create a branch for each piece of data
tree.Branch( 'tluHighWord' , highWord , "HighWord/l")
tree.Branch( 'tluLowWord' , lowWord , "LowWord/l")
tree.Branch( 'tluTimeStamp' , timeStamp , "TimeStamp/l")
tree.Branch( 'tluBufPos' , bufPos , "Bufpos/s")
tree.Branch( 'tluEvtNumber' , evtNumber , "EvtNumber/i")
tree.Branch( 'tluEvtType' , evtType , "EvtType/b")
tree.Branch( 'tluTrigFired' , trigsFired, "TrigsFired/b")
# Initialize TLU registers
initTLU( uhalDevice = hw, pychipsBoard = board, listenForTelescopeShutter = options.listenForTelescopeShutter, pulseDelay = options.pulseDelay, pulseStretch = options.pulseStretch, triggerPattern = options.triggerPattern , DUTMask = options.DUTMask, ignoreDUTBusy = options.ignoreDUTBusy , triggerInterval = options.triggerInterval, thresholdVoltage = options.thresholdVoltage )
loopWait = 0.1
oldEvtNumber = 0
oldPreVetotriggerCount = board.read("PreVetoTriggersR")
oldPostVetotriggerCount = board.read("PostVetoTriggersR")
oldThresholdCounter0 =0
oldThresholdCounter1 =0
oldThresholdCounter2 =0
oldThresholdCounter3 =0
print "STARTING POLLING LOOP"
eventFifoFillLevel = 0
loopRunning = True
runStarted = False
oldTime = time.time()
# Save old terminal settings
oldTermSettings = termios.tcgetattr(sys.stdin)
tty.setcbreak(sys.stdin.fileno())
while loopRunning:
if isData():
c = sys.stdin.read(1)
print "\tGOT INPUT:", c
if c == 't':
loopRunning = False
print "\tTERMINATING LOOP"
elif c == 'c':
runStarted = True
print "\tSTARTING RUN"
startTLU( uhalDevice = hw, pychipsBoard = board, writeTimestamps = ( options.writeTimestamps == "True" ) )
elif c == 'f':
# runStarted = True
print "\tSTOPPING TRIGGERS"
stopTLU( uhalDevice = hw, pychipsBoard = board )
if runStarted:
eventFifoFillLevel = hw.getNode("eventBuffer.EventFifoFillLevel").read()
preVetotriggerCount = hw.getNode("triggerLogic.PreVetoTriggersR").read()
postVetotriggerCount = hw.getNode("triggerLogic.PostVetoTriggersR").read()
timestampHigh = hw.getNode("Event_Formatter.CurrentTimestampHR").read()
timestampLow = hw.getNode("Event_Formatter.CurrentTimestampLR").read()
thresholdCounter0 = hw.getNode("triggerInputs.ThrCount0R").read()
thresholdCounter1 = hw.getNode("triggerInputs.ThrCount1R").read()
thresholdCounter2 = hw.getNode("triggerInputs.ThrCount2R").read()
thresholdCounter3 = hw.getNode("triggerInputs.ThrCount3R").read()
hw.dispatch()
newTime = time.time()
timeDelta = newTime - oldTime
oldTime = newTime
#print "time delta = " , timeDelta
preVetoFreq = (preVetotriggerCount-oldPreVetotriggerCount)/timeDelta
postVetoFreq = (postVetotriggerCount-oldPostVetotriggerCount)/timeDelta
oldPreVetotriggerCount = preVetotriggerCount
oldPostVetotriggerCount = postVetotriggerCount
deltaCounts0 = thresholdCounter0 - oldThresholdCounter0
oldThresholdCounter0 = thresholdCounter0
deltaCounts1 = thresholdCounter1 - oldThresholdCounter1
oldThresholdCounter1 = thresholdCounter1
deltaCounts2 = thresholdCounter2 - oldThresholdCounter2
oldThresholdCounter2 = thresholdCounter2
deltaCounts3 = thresholdCounter3 - oldThresholdCounter3
oldThresholdCounter3 = thresholdCounter3
print "pre , post veto triggers , pre , post frequency = " , preVetotriggerCount , postVetotriggerCount , preVetoFreq , postVetoFreq
print "CURRENT TIMESTAMP HIGH, LOW (hex) = " , hex(timestampHigh) , hex(timestampLow)
print "Input counts 0,1,2,3 = " , thresholdCounter0 , thresholdCounter1 , thresholdCounter2 , thresholdCounter3
print "Input freq (Hz) 0,1,2,3 = " , deltaCounts0/timeDelta , deltaCounts1/timeDelta , deltaCounts2/timeDelta , deltaCounts3/timeDelta
nEvents = int(eventFifoFillLevel)//4 # only read out whole events ( 4 x 32-bit words )
wordsToRead = nEvents*4
print "FIFO FILL LEVEL= " , eventFifoFillLevel
print "# EVENTS IN FIFO = ",nEvents
print "WORDS TO READ FROM FIFO = ",wordsToRead
# get timestamp data and fifo fill in same outgoing packet.
timestampData = hw.getNode("eventBuffer.EventFifoData").readBlock(wordsToRead)
hw.dispatch()
# print timestampData
for bufPos in range (0, nEvents ):
lowWord = timestampData[bufPos*4 + 1] + 0x100000000* timestampData[ (bufPos*4) + 0] # timestamp
highWord = timestampData[bufPos*4 + 3] + 0x100000000* timestampData[ (bufPos*4) + 2] # evt number
evtNumber = timestampData[bufPos*4 + 3]
if evtNumber != ( oldEvtNumber + 1 ):
print "***WARNING *** Non sqeuential event numbers *** , evt,oldEvt = ", evtNumber , oldEvtNumber
oldEvtNumber = evtNumber
timeStamp = lowWord & 0xFFFFFFFFFFFF
evtType = timestampData[ (bufPos*4) + 0] >> 28
trigsFired = (timestampData[ (bufPos*4) + 0] >> 16) & 0xFFF
if (options.printTimestamps == "True" ):
print "bufferPos, highWord , lowWord , event-number , timestamp , evtType = %x %016x %016x %08x %012x %01x %03x" % ( bufPos , highWord , lowWord, evtNumber , timeStamp , evtType , trigsFired)
# Fill root branch - see example in http://wlav.web.cern.ch/wlav/pyroot/tpytree.html : write raw data and decoded data for now.
tree.Fill()
time.sleep( loopWait)
# Fixme - at the moment infinite loop.
preVetotriggerCount = board.read("PreVetoTriggersR")
postVetotriggerCount = board.read("PostVetoTriggersR")
print "EXIT POLLING LOOP"
print "\nTRIGGER COUNT AT THE END OF RUN [pre, post]:" , preVetotriggerCount , postVetotriggerCount
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, oldTermSettings)
f.Write()
f.Close()
# -*- coding: utf-8 -*-
# miniTLU test script
#from PyChipsUser import *
from FmcTluI2c import *
import uhal
import sys
import time
# from ROOT import TFile, TTree
# from ROOT import gROOT
from datetime import datetime
from TLU import TLU
# Use to have interactive shell
import cmd
class MyPrompt(cmd.Cmd):
def do_startRun(self, args):
"""Starts the TLU run"""
print "COMMAND RECEIVED: STARTING TLU RUN"
startTLU( uhalDevice = self.hw, pychipsBoard = self.board, writeTimestamps = ( options.writeTimestamps == "True" ) )
#print self.hw
def do_stopRun(self, args):
"""Stops the TLU run"""
print "COMMAND RECEIVED: STOP TLU RUN"
#stopTLU( uhalDevice = hw, pychipsBoard = board )
def do_quit(self, args):
"""Quits the program."""
print "COMMAND RECEIVED: QUITTING SCRIPT."
#raise SystemExit
return True
# # Override methods in Cmd object ##
# def preloop(self):
# """Initialization before prompting user for commands.
# Despite the claims in the Cmd documentaion, Cmd.preloop() is not a stub.
# """
# cmd.Cmd.preloop(self) # # sets up command completion
# self._hist = [] # # No history yet
# self._locals = {} # # Initialize execution namespace for user
# self._globals = {}
# print "\nINITIALIZING"
# now = datetime.now().strftime('%Y-%m-%dT%H_%M_%S')
# default_filename = './rootfiles/tluData_' + now + '.root'
# print "SETTING UP AIDA TLU TO SUPPLY CLOCK AND TRIGGER TO TORCH READOUT\n"
# self.manager = uhal.ConnectionManager("file://./connection.xml")
# self.hw = self.manager.getDevice("minitlu")
# self.device_id = self.hw.id()
#
# # Point to TLU in Pychips
# self.bAddrTab = AddressTable("./aida_mini_tlu_addr_map.txt")
#
# # Assume DIP-switch controlled address. Switches at 2
# self.board = ChipsBusUdp(self.bAddrTab,"192.168.200.32",50001)
#################################################
if __name__ == "__main__":
TLU= TLU("tlu", "file://./TLUconnection.xml")
TLU.initialize()
logdata= True
TLU.start(logdata)
time.sleep(0.2)
TLU.stop()
# prompt = MyPrompt()
# prompt.prompt = '>> '
# prompt.cmdloop("Welcome to miniTLU test console.\nType HELP for a list of commands.")
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.mlab as mlab
print "TEST.py"
myFile= "./500ns_23ns.txt"
with open(myFile) as f:
nsDeltas = map(float, f)
P= 1000000000 #display in ns
nsDeltas = [x * P for x in nsDeltas]
centerRange= 25
windowsns= 5
minRange= centerRange-windowsns
maxRange= centerRange+windowsns
plt.hist(nsDeltas, 60, range=[minRange, maxRange], facecolor='blue', align='mid', alpha= 0.75)
#plt.hist(nsDeltas, 100, normed=True, facecolor='blue', align='mid', alpha=0.75)
#plt.xlim((min(nsDeltas), max(nsDeltas)))
plt.xlabel('Time (ns)')
plt.ylabel('Entries')
plt.title('Histogram DeltaTime')
plt.grid(True)
#Superimpose Gauss
mean = np.mean(nsDeltas)
variance = np.var(nsDeltas)
sigma = np.sqrt(variance)
x = np.linspace(min(nsDeltas), max(nsDeltas), 100)
plt.plot(x, mlab.normpdf(x, mean, sigma))
print (mean, sigma)
#Display plot
plt.show()
# miniTLU test script
from FmcTluI2c import *
import uhal
import sys
import time
from I2CuHal import I2CCore
from miniTLU import MiniTLU
from datetime import datetime
if __name__ == "__main__":
print "\tTEST TLU SCRIPT"
miniTLU= MiniTLU("minitlu", "file://./connection.xml")
#(self, target, wclk, i2cclk, name="i2c", delay=None)
TLU_I2C= I2CCore(miniTLU.hw, 10, 5, "i2c_master", None)
TLU_I2C.state()
#READ CONTENT OF EEPROM ON 24AA02E48 (0xFA - 0XFF)
mystop= 1
time.sleep(0.1)
myaddr= [0xfa]
TLU_I2C.write( 0x50, myaddr, mystop)
res=TLU_I2C.read( 0x50, 6)
print "Checkin EEPROM:"
result="\t"
for iaddr in res:
result+="%02x "%(iaddr)
print result
#SCAN I2C ADDRESSES
#WRITE PROM
#WRITE DAC
#Convert required threshold voltage to DAC code
#def convert_voltage_to_dac(self, desiredVoltage, Vref=1.300):
print("Writing DAC setting:")
Vref= 1.300
desiredVoltage= 3.3
channel= 0
i2cSlaveAddrDac = 0x1F
vrefOn= 0
Vdaq = ( desiredVoltage + Vref ) / 2
dacCode = 0xFFFF * Vdaq / Vref
dacCode= 0x391d
print "\tVreq:", desiredVoltage
print "\tDAC code:" , dacCode
print "\tCH:", channel
print "\tIntRef:", vrefOn
#Set DAC value
#def set_dac(self,channel,value , vrefOn = 0 , i2cSlaveAddrDac = 0x1F):
if channel<0 or channel>7:
print "set_dac ERROR: channel",channel,"not in range 0-7 (bit mask)"
##return -1
if dacCode<0 or dacCode>0xFFFF:
print "set_dac ERROR: value",dacCode ,"not in range 0-0xFFFF"
##return -1
# AD5665R chip with A0,A1 tied to ground
#i2cSlaveAddrDac = 0x1F # seven bit address, binary 00011111
# print "I2C address of DAC = " , hex(i2cSlaveAddrDac)
# dac = RawI2cAccess(self.i2cBusProps, i2cSlaveAddrDac)
# # if we want to enable internal voltage reference:
if vrefOn:
# enter vref-on mode:
print "\tTurning internal reference ON"
#dac.write([0x38,0x00,0x01])
TLU_I2C.write( i2cSlaveAddrDac, [0x38,0x00,0x01], 0)
else:
print "\tTurning internal reference OFF"
#dac.write([0x38,0x00,0x00])
TLU_I2C.write( i2cSlaveAddrDac, [0x38,0x00,0x00], 0)
# Now set the actual value
sequence=[( 0x18 + ( channel &0x7 ) ) , int(dacCode/256)&0xff , int(dacCode)&0xff]
print "\tWriting byte sequence:", sequence
TLU_I2C.write( i2cSlaveAddrDac, sequence, 0)
#
# Script to exercise AIDA mini-TLU
#
# David Cussans, December 2012
#
# Nasty hack - use both PyChips and uHAL ( for block read ... )
from PyChipsUser import *
from FmcTluI2c import *
import sys
import time
# Point to TLU in Pychips
bAddrTab = AddressTable("./aida_mini_tlu_addr_map.txt")
# Assume DIP-switch controlled address. Switches at 2
board = ChipsBusUdp(bAddrTab,"192.168.200.32",50001)
# Check the bus for I2C devices
boardi2c = FmcTluI2c(board)
firmwareID=board.read("FirmwareId")
print "Firmware (from PyChips) = " , hex(firmwareID)
print "Scanning I2C bus:"
scanResults = boardi2c.i2c_scan()
print scanResults
boardId = boardi2c.get_serial_number()
print "FMC-TLU serial number = " , boardId
resetClocks = 0
clockStatus = board.read("LogicClocksCSR")
print "Clock status = " , hex(clockStatus)
if resetClocks:
print "Resetting clocks"
board.write("LogicRst", 1 )
clockStatus = board.read("LogicClocksCSR")
print "Clock status after reset = " , hex(clockStatus)
board.write("InternalTriggerIntervalW",0)
print "Enabling DUT 0 and 1"
board.write("DUTMaskW",3)
DUTMask = board.read("DUTMaskR")
print "DUTMaskR = " , DUTMask
print "Ignore veto on DUT 0 and 1"
board.write("IgnoreDUTBusyW",3)
IgnoreDUTBusy = board.read("IgnoreDUTBusyR")
print "IgnoreDUTBusyR = " , IgnoreDUTBusy
print "Turning off software trigger veto"
board.write("TriggerVetoW",0)
print "Reseting FIFO"
board.write("EventFifoCSR",0x2)
eventFifoFillLevel = board.read("EventFifoFillLevel")
print "FIFO fill level after resetting FIFO = " , eventFifoFillLevel
print "Enabling data recording"
board.write("Enable_Record_Data",1)
#print "Enabling handshake: No-handshake"
#board.write("HandshakeTypeW",1)
#TriggerInterval = 400000
TriggerInterval = 0
print "Setting internal trigger interval to " , TriggerInterval
board.write("InternalTriggerIntervalW",TriggerInterval) #0->Internal pulse generator disabled. Any other value will generate pulses with a frequency of n*6.25ns
trigInterval = board.read("InternalTriggerIntervalR")
print "Trigger interval read back as ", trigInterval
print "Setting TPix_maskexternal to ignore external shutter and T0"
board.write("TPix_maskexternal",0x0003)
numLoops = 500000
oldEvtNumber = 0
for iLoop in range(0,numLoops):
board.write("TPix_T0", 0x0001)
# time.sleep( 1.0)
......@@ -45,20 +45,20 @@ class TLU:
self.IC6=PCA9539PW(self.TLU_I2C, 0x74)
self.IC6.setInvertReg(0, 0x00)# 0= normal, 1= inverted
self.IC6.setIOReg(0, 0x00)# 0= output, 1= input
self.IC6.setOutputs(0, 0xAA)# If output, set to XX
self.IC6.setOutputs(0, 0x77)# If output, set to XX
self.IC6.setInvertReg(1, 0x00)# 0= normal, 1= inverted
self.IC6.setIOReg(1, 0x00)# 0= output, 1= input
self.IC6.setOutputs(1, 0xAA)# If output, set to XX
self.IC6.setOutputs(1, 0x77)# If output, set to XX
self.IC7=PCA9539PW(self.TLU_I2C, 0x75)
self.IC7.setInvertReg(0, 0x00)# 0= normal, 1= inverted
self.IC7.setIOReg(0, 0x00)# 0= output, 1= input
self.IC7.setOutputs(0, 0x0F)# If output, set to XX
self.IC7.setOutputs(0, 0x00)# If output, set to XX
self.IC7.setInvertReg(1, 0x00)# 0= normal, 1= inverted
self.IC7.setIOReg(1, 0x00)# 0= output, 1= input
self.IC7.setOutputs(1, 0x50)# If output, set to XX
self.IC7.setOutputs(1, 0xB0)# If output, set to XX
##################################################################################################################################
......@@ -645,9 +645,9 @@ class TLU:
self.setDUTmask(DUTMask)
#
# # # Set mode
DUTMode= 0xFFFFFFFF
DUTMode= 0xFFFFFFFC ####
self.setMode(DUTMode)
# # # Set modifier
modifier = int("0xFF",16)
self.setModeModifier(modifier)
......
......@@ -65,7 +65,7 @@ if __name__ == "__main__":
logdata= True
TLU.start(logdata)
time.sleep(1.5)
time.sleep(5)
TLU.stop(False, False)
# prompt = MyPrompt()
# prompt.prompt = '>> '
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment