Commit 33873b2c authored by David Cussans's avatar David Cussans

Used 2to3 and autopep8 to convert Python scripts from Python2 to Python3 (needed by Warwick)

parent 7cd338b5
......@@ -14,72 +14,69 @@ hw = manager.getDevice("tlu")
# hw.getNode("A").write(255)
reg = hw.getNode("version").read()
hw.dispatch()
print "CHECK REG= ", hex(reg)
print("CHECK REG= ", hex(reg))
# #First I2C core
print ("Instantiating master I2C core:")
master_I2C= I2CCore(hw, 10, 5, "i2c_master", None)
print("Instantiating master I2C core:")
master_I2C = I2CCore(hw, 10, 5, "i2c_master", None)
master_I2C.state()
#
# #######################################
enableCore= False #Only need to run this once, after power-up
enableCore = False # 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 = 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
mystop = False
mycmd = [0x01]
master_I2C.write(myslave, mycmd, mystop)
res = master_I2C.read(myslave, nwords)
print("\tPost RegDir: ", res)
#DAC CONFIGURATION BEGIN
# DAC CONFIGURATION BEGIN
if (False):
zeDAC1=AD5665R(master_I2C, 0x1C)
zeDAC1.setIntRef(intRef= False, verbose= True)
zeDAC1.writeDAC(0x0, 7, verbose= True)#7626
zeDAC1 = AD5665R(master_I2C, 0x1C)
zeDAC1.setIntRef(intRef=False, verbose=True)
zeDAC1.writeDAC(0x0, 7, verbose=True) # 7626
if (True):
# #I2C EXPANDER CONFIGURATION BEGIN
IC6=PCA9539PW(master_I2C, 0x76)
#BANK 0
IC6.setInvertReg(0, 0x00)# 0= normal
IC6.setIOReg(0, 0x00)# 0= output <<<<<<<<<<<<<<<<<<<
IC6.setOutputs(0, 0x00)
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, 0x00)# 0= output <<<<<<<<<<<<<<<<<<<
IC6.setOutputs(1, 0x00)
res= IC6.getInputs(1)
print "IC6 read back bank 1: 0x%X" % res[0]
# # #
IC7=PCA9539PW(master_I2C, 0x77)
#BANK 0
IC7.setInvertReg(0, 0x00)# 0= normal
IC7.setIOReg(0, 0x00)# 0= output <<<<<<<<<<<<<<<<<<<
IC7.setOutputs(0, 0x00)
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, 0x00)# 0= output <<<<<<<<<<<<<<<<<<<
IC7.setOutputs(1, 0x00)
res= IC7.getInputs(1)
print "IC7 read back bank 1: 0x%X" % res[0]
# #I2C EXPANDER CONFIGURATION END
# #I2C EXPANDER CONFIGURATION BEGIN
IC6 = PCA9539PW(master_I2C, 0x76)
# BANK 0
IC6.setInvertReg(0, 0x00) # 0= normal
IC6.setIOReg(0, 0x00) # 0= output <<<<<<<<<<<<<<<<<<<
IC6.setOutputs(0, 0x00)
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, 0x00) # 0= output <<<<<<<<<<<<<<<<<<<
IC6.setOutputs(1, 0x00)
res = IC6.getInputs(1)
print("IC6 read back bank 1: 0x%X" % res[0])
# # #
IC7 = PCA9539PW(master_I2C, 0x77)
# BANK 0
IC7.setInvertReg(0, 0x00) # 0= normal
IC7.setIOReg(0, 0x00) # 0= output <<<<<<<<<<<<<<<<<<<
IC7.setOutputs(0, 0x00)
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, 0x00) # 0= output <<<<<<<<<<<<<<<<<<<
IC7.setOutputs(1, 0x00)
res = IC7.getInputs(1)
print("IC7 read back bank 1: 0x%X" % res[0])
# #I2C EXPANDER CONFIGURATION END
......@@ -7,7 +7,7 @@ from si5345 import si5345
from AD5665R import AD5665R
from PCA9539PW import PCA9539PW
from E24AA025E48T import E24AA025E48T
from I2CDISP import LCD_ada #Library for display
from I2CDISP import LCD_ada # Library for display
manager = uhal.ConnectionManager("file://./TLUconnection.xml")
hw = manager.getDevice("tlu")
......@@ -15,34 +15,31 @@ hw = manager.getDevice("tlu")
# hw.getNode("A").write(255)
reg = hw.getNode("version").read()
hw.dispatch()
print "CHECK REG= ", hex(reg)
print("CHECK REG= ", hex(reg))
# #First I2C core
print ("Instantiating master I2C core:")
master_I2C= I2CCore(hw, 10, 5, "i2c_master", None)
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
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
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)
......@@ -62,10 +59,10 @@ if (enableCore):
# #######################################
#Second I2C core
# Second I2C core
#print ("Instantiating SFP I2C core:")
#clock_I2C= I2CCore(hw, 10, 5, "i2c_sfp", None)
#clock_I2C.state()
# clock_I2C.state()
# #Third I2C core
# print ("Instantiating clock I2C core:")
......@@ -90,104 +87,104 @@ if (enableCore):
#
#CLOCK CONFIGURATION BEGIN
zeClock=si5345(master_I2C, 0x68)
res= zeClock.getDeviceVersion()
# CLOCK CONFIGURATION BEGIN
zeClock = si5345(master_I2C, 0x68)
res = zeClock.getDeviceVersion()
zeClock.checkDesignID()
#zeClock.setPage(0, True)
#zeClock.getPage(True)
doClock= False
# zeClock.getPage(True)
doClock = False
if (doClock):
clkRegList= zeClock.parse_clk("./../../bitFiles/TLU_CLK_Config_v1e.txt")
zeClock.writeConfiguration(clkRegList)######
zeClock.writeRegister(0x0536, [0x0A]) #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 (0x000E): 0x%X" % lol[0]
los= zeClock.readRegister(0x000D, 1)
print " Clock LOS (0x000D): 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"
clkRegList = zeClock.parse_clk("./../../bitFiles/TLU_CLK_Config_v1e.txt")
zeClock.writeConfiguration(clkRegList)
zeClock.writeRegister(0x0536, [0x0A]) # 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 (0x000E): 0x%X" % lol[0])
los = zeClock.readRegister(0x000D, 1)
print(" Clock LOS (0x000D): 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
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, 0x00)# 0= output <<<<<<<<<<<<<<<<<<<
IC6.setOutputs(0, 0x77)#77
res= IC6.getInputs(0)
print "\tIC6 read back bank 0: 0x%X" % res[0]
IC6 = PCA9539PW(master_I2C, 0x74)
# BANK 0
IC6.setInvertReg(0, 0x00) # 0= normal
IC6.setIOReg(0, 0x00) # 0= output <<<<<<<<<<<<<<<<<<<
IC6.setOutputs(0, 0x77) # 77
res = IC6.getInputs(0)
print("\tIC6 read back bank 0: 0x%X" % res[0])
#
#BANK 1
IC6.setInvertReg(1, 0x00)# 0= normal
IC6.setIOReg(1, 0x00)# 0= output <<<<<<<<<<<<<<<<<<<
IC6.setOutputs(1, 0x77)#77
res= IC6.getInputs(1)
print "\tIC6 read back bank 1: 0x%X" % res[0]
# BANK 1
IC6.setInvertReg(1, 0x00) # 0= normal
IC6.setIOReg(1, 0x00) # 0= output <<<<<<<<<<<<<<<<<<<
IC6.setOutputs(1, 0x77) # 77
res = IC6.getInputs(1)
print("\tIC6 read back bank 1: 0x%X" % res[0])
# # #
IC7=PCA9539PW(master_I2C, 0x75)
#BANK 0
IC7.setInvertReg(0, 0x00)# 0= normal
IC7.setIOReg(0, 0x00)# 0= output <<<<<<<<<<<<<<<<<<<
IC7 = PCA9539PW(master_I2C, 0x75)
# BANK 0
IC7.setInvertReg(0, 0x00) # 0= normal
IC7.setIOReg(0, 0x00) # 0= output <<<<<<<<<<<<<<<<<<<
IC7.setOutputs(0, 0xF0)
res= IC7.getInputs(0)
print "\tIC7 read back bank 0: 0x%X" % res[0]
res = IC7.getInputs(0)
print("\tIC7 read back bank 0: 0x%X" % res[0])
#
#BANK 1
IC7.setInvertReg(1, 0x00)# 0= normal
IC7.setIOReg(1, 0x00)# 0= output <<<<<<<<<<<<<<<<<<<
# BANK 1
IC7.setInvertReg(1, 0x00) # 0= normal
IC7.setIOReg(1, 0x00) # 0= output <<<<<<<<<<<<<<<<<<<
IC7.setOutputs(1, 0xAF)
res= IC7.getInputs(1)
print "\tIC7 read back bank 1: 0x%X" % res[0]
res = IC7.getInputs(1)
print("\tIC7 read back bank 1: 0x%X" % res[0])
# #I2C EXPANDER CONFIGURATION END
#Instantiate Display
doDisplaytest= False
# Instantiate Display
doDisplaytest = False
if doDisplaytest:
DISP=LCD_ada(master_I2C, 0x20) #3A
#self.DISP.clear()
DISP.test()
DISP = LCD_ada(master_I2C, 0x20) # 3A
# self.DISP.clear()
DISP.test()
# #Reset counters
#cmd = int("0x0", 16) #write 0x2 to reset
#hw.getNode("triggerInputs.SerdesRstW").write(cmd)
# 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
# hw.dispatch()
# print "Trigger Reset: 0x%X" % restatus
# Read trigger inputs
#myreg= [-1, -1, -1, -1, -1, -1]
#for inputN in range(0, 6):
# 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
# Read ev formatter
#cmd = int("0x0", 16) #
##hw.getNode("Event_Formatter.Enable_Record_Data").write(cmd)
# 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
# hw.dispatch()
# print "Event Formatter Record: 0x%X" % efstatus
This diff is collapsed.
This diff is collapsed.
......@@ -17,7 +17,7 @@ from TLU_v1e import TLU
import cmd
# Use to have config file parser
import ConfigParser
import configparser
# Use root
from ROOT import TFile, TTree, gROOT, AddressOf
......@@ -25,7 +25,7 @@ from ROOT import *
import numpy as numpy
## Define class that creates the command user inteface
# Define class that creates the command user inteface
class MyPrompt(cmd.Cmd):
# def do_initialise(self, args):
......@@ -44,32 +44,31 @@ class MyPrompt(cmd.Cmd):
# print "\t Could not retrieve INI data."
# return
def do_configure(self, args):
"""Processes the CONF file and writes its values to the TLU. To use a specific file type:\n
parseIni path/to/filename.conf\n
(without quotation marks)"""
print "==== COMMAND RECEIVED: PARSE CONFIG"
#self.testme()
parsed_cfg= self.open_cfg_file(args, "./localConf.conf")
print("==== COMMAND RECEIVED: PARSE CONFIG")
# self.testme()
parsed_cfg = self.open_cfg_file(args, "./localConf.conf")
try:
theID = parsed_cfg.getint("Producer.fmctlu", "confid")
print "\t", theID
print("\t", theID)
TLU.configure(parsed_cfg)
except IOError:
print "\t Could not retrieve CONF data."
print("\t Could not retrieve CONF data.")
return
def do_i2c(self, args):
arglist = args.split()
arglist = args.split()
if len(arglist) == 0:
print "\tno command specified"
print("\tno command specified")
else:
i2ccmd= arglist[0]
i2ccmd = arglist[0]
results = list(map(int, arglist))
TLU.DISP.writeSomething(results)
print "Sending i2c command to display"
return
TLU.DISP.writeSomething(results)
print("Sending i2c command to display")
return
def do_id(self, args):
"""Interrogates the TLU and prints it unique ID on screen"""
......@@ -85,40 +84,41 @@ class MyPrompt(cmd.Cmd):
def do_startRun(self, args):
"""Starts the TLU run. If a number is specified, this number will be appended to the file name as Run_#"""
print "==== COMMAND RECEIVED: STARTING TLU RUN"
#startTLU( uhalDevice = self.hw, pychipsBoard = self.board, writeTimestamps = ( options.writeTimestamps == "True" ) )
print("==== COMMAND RECEIVED: STARTING TLU RUN")
#startTLU( uhalDevice = self.hw, pychipsBoard = self.board, writeTimestamps = ( options.writeTimestamps == "True" ) )
arglist = args.split()
if len(arglist) == 0:
print "\tno run# specified, using 1"
runN= 1
print("\tno run# specified, using 1")
runN = 1
else:
runN= arglist[0]
runN = arglist[0]
logdata= True
logdata = True
#TLU.start(logdata)
if (TLU.isRunning): #Prevent double start
print " Run already in progress"
# TLU.start(logdata)
if (TLU.isRunning): # Prevent double start
print(" Run already in progress")
return
else:
now = datetime.now().strftime('%Y%m%d_%H%M%S')
default_filename = "./datafiles/"+ now + "_tluData_" + str(runN) + ".root"
rootFname= default_filename
print "OPENING ROOT FILE:", rootFname
self.root_file = TFile( rootFname, 'RECREATE' )
default_filename = "./datafiles/" + \
now + "_tluData_" + str(runN) + ".root"
rootFname = default_filename
print("OPENING ROOT FILE:", rootFname)
self.root_file = TFile(rootFname, 'RECREATE')
# Create a root "tree"
root_tree = TTree( 'T', 'TLU Data' )
root_tree = TTree('T', 'TLU Data')
#highWord =0
#lowWord =0
#evtNumber=0
#timeStamp=0
#evtType=0
#trigsFired=0
# evtNumber=0
# timeStamp=0
# evtType=0
# trigsFired=0
#bufPos = 0
#https://root-forum.cern.ch/t/long-integer/1961/2
# https://root-forum.cern.ch/t/long-integer/1961/2
gROOT.ProcessLine(
"struct MyStruct {\
"struct MyStruct {\
UInt_t raw0;\
UInt_t raw1;\
UInt_t raw2;\
......@@ -129,13 +129,13 @@ class MyPrompt(cmd.Cmd):
ULong64_t tluTimeStamp;\
UChar_t tluEvtType;\
UChar_t tluTrigFired;\
};" );
mystruct= MyStruct()
};")
mystruct = MyStruct()
# Create a branch for each piece of data
root_tree.Branch('EVENTS', mystruct, 'raw0/i:raw1/i:raw2/i:raw3/i:raw4/i:raw5/i:evtNumber/i:tluTimeStamp/l:tluEvtType/b:tluTrigFired/b' )
root_tree.Branch(
'EVENTS', mystruct, 'raw0/i:raw1/i:raw2/i:raw3/i:raw4/i:raw5/i:evtNumber/i:tluTimeStamp/l:tluEvtType/b:tluTrigFired/b')
# root_tree.Branch( 'tluHighWord' , highWord , "HighWord/l")
# root_tree.Branch( 'tluLowWord' , lowWord , "LowWord/l")
# root_tree.Branch( 'tluExtWord' , extWord , "ExtWord/l")
......@@ -144,36 +144,36 @@ class MyPrompt(cmd.Cmd):
# root_tree.Branch( 'tluEvtNumber' , evtNumber , "EvtNumber/i")
# root_tree.Branch( 'tluEvtType' , evtType , "EvtType/b")
# root_tree.Branch( 'tluTrigFired' , trigsFired, "TrigsFired/b")
#self.root_file.Write()
# self.root_file.Write()
daq_thread= threading.Thread(target = TLU.start, args=(logdata, runN, mystruct, root_tree))
daq_thread = threading.Thread(
target=TLU.start, args=(logdata, runN, mystruct, root_tree))
daq_thread.start()
def do_endRun(self, args):
"""Stops the TLU run"""
print "==== COMMAND RECEIVED: STOP TLU RUN"
"""Stops the TLU run"""
print("==== COMMAND RECEIVED: STOP TLU RUN")
if TLU.isRunning:
TLU.isRunning= False
TLU.isRunning = False
TLU.stop(False, False)
self.root_file.Write()
self.root_file.Close()
else:
print " No run to stop"
print(" No run to stop")
def do_quit(self, args):
"""Quits the program."""
print "==== COMMAND RECEIVED: QUITTING TLU CONSOLE"
print("==== COMMAND RECEIVED: QUITTING TLU CONSOLE")
if TLU.isRunning:
TLU.isRunning= False
TLU.isRunning = False
TLU.stop(False, False)
self.root_file.Write()
self.root_file.Close()
print "Terminating run"
return True
print("Terminating run")
return True
def testme(self):
print "This is a test"
print("This is a test")
def open_cfg_file(self, args, default_file):
# Parse the user arguments, attempts to opent the file and performs a (minimal)
......@@ -181,22 +181,22 @@ class MyPrompt(cmd.Cmd):
arglist = args.split()
if len(arglist) == 0:
print "\tno file specified, using default"
fileName= default_file
print "\t", fileName
print("\tno file specified, using default")
fileName = default_file
print("\t", fileName)
else:
fileName= arglist[0]
fileName = arglist[0]
if len(arglist) > 1:
print "\tinvalid: too many arguments. Max 1."
print("\tinvalid: too many arguments. Max 1.")
return
parsed_file = ConfigParser.RawConfigParser()
parsed_file = configparser.RawConfigParser()
try:
with open(fileName) as f:
parsed_file.readfp(f)
print "\t", parsed_file.sections()
print("\t", parsed_file.sections())
except IOError:
print "\t Error while parsing the specified file."
print("\t Error while parsing the specified file.")
return
return parsed_file
......@@ -226,21 +226,21 @@ class MyPrompt(cmd.Cmd):
#################################################
if __name__ == "__main__":
print "TLU v1E MAIN"
print("TLU v1E MAIN")
prompt = MyPrompt()
prompt.prompt = '>> '
parsed_ini= prompt.open_cfg_file("", "./localIni.ini")
TLU= TLU("tlu", "file://./TLUconnection.xml", parsed_ini)
parsed_ini = prompt.open_cfg_file("", "./localIni.ini")
TLU = TLU("tlu", "file://./TLUconnection.xml", parsed_ini)
###TLU.configure(parsed_cfg)
# TLU.configure(parsed_cfg)
###logdata= True
###TLU.start(logdata)
###time.sleep(5)
# TLU.start(logdata)
# time.sleep(5)
###TLU.stop(False, False)
# Start interactive prompt
print "===================================================================="
print "==========================TLU TEST CONSOLE=========================="
print "===================================================================="
print("====================================================================")
print("==========================TLU TEST CONSOLE==========================")
print("====================================================================")
prompt.cmdloop("Type 'help' for a list of commands.")
......@@ -21,5 +21,5 @@ echo "============"
echo "STARTING PYTHON SCRIPT FOR TLU"
#python $CURRENT_DIR/startTLU_v8.py $@
python startTLU_v1e.py $@
python3 startTLU_v1e.py $@
#python testTLU_script.py
This diff is collapsed.
......@@ -2,19 +2,20 @@ import matplotlib.pyplot as plt
import numpy as np
import matplotlib.mlab as mlab
print "TEST.py"
myFile= "./500ns_23ns.txt"
print("TEST.py")
myFile = "./500ns_23ns.txt"
with open(myFile) as f:
nsDeltas = map(float, f)
nsDeltas = list(map(float, f))
P= 1000000000 #display in ns
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)
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)')
......@@ -22,13 +23,13 @@ plt.ylabel('Entries')
plt.title('Histogram DeltaTime')
plt.grid(True)
#Superimpose Gauss
# 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)
print((mean, sigma))
#Display plot
# Display plot
plt.show()
......@@ -9,56 +9,54 @@ 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)
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
# 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"
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
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):
# 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
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
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
# 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
# i2cSlaveAddrDac = 0x1F # seven bit address, binary 00011111
# print "I2C address of DAC = " , hex(i2cSlaveAddrDac)
# dac = RawI2cAccess(self.i2cBusProps, i2cSlaveAddrDac)
......@@ -66,14 +64,15 @@ if __name__ == "__main__":
if vrefOn:
# enter vref-on mode:
print "\tTurning internal reference ON"
#dac.write([0x38,0x00,0x01])
TLU_I2C.write( i2cSlaveAddrDac, [0x38,0x00,0x01], 0)
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)
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)
sequence = [(0x18 + (channel & 0x7)), int(dacCode/256)
& 0xff, int(dacCode) & 0xff]
print("\tWriting byte sequence:", sequence)
TLU_I2C.write(i2cSlaveAddrDac, sequence, 0)
......@@ -2,7 +2,7 @@
# Script to exercise AIDA mini-TLU
#
# David Cussans, December 2012
#
#
# Nasty hack - use both PyChips and uHAL ( for block read ... )
from PyChipsUser import *
......@@ -14,78 +14,78 @@ 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)
# 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")
firmwareID = board.read("FirmwareId")
print "Firmware (from PyChips) = " , hex(firmwareID)
print("Firmware (from PyChips) = ", hex(firmwareID))
print "Scanning I2C bus:"
print("Scanning I2C bus:")
scanResults = boardi2c.i2c_scan()
print scanResults
print(scanResults)
boardId = boardi2c.get_serial_number()
print "FMC-TLU serial number = " , boardId
print("FMC-TLU serial number = ", boardId)
resetClocks = 0
clockStatus = board.read("LogicClocksCSR")
print "Clock status = " , hex(clockStatus)
print("Clock status = ", hex(clockStatus))
if resetClocks:
print "Resetting clocks"
board.write("LogicRst", 1 )
print("Resetting clocks")
board.write("LogicRst", 1)
clockStatus = board.read("LogicClocksCSR")
print "Clock status after reset = " , hex(clockStatus)
print("Clock status after reset = ", hex(clockStatus))
board.write("InternalTriggerIntervalW",0)
board.write("InternalTriggerIntervalW", 0)
print "Enabling DUT 0 and 1"
board.write("DUTMaskW",3)
print("Enabling DUT 0 and 1")
board.write("DUTMaskW", 3)
DUTMask = board.read("DUTMaskR")
print "DUTMaskR = " , DUTMask
print("DUTMaskR = ", DUTMask)
print "Ignore veto on DUT 0 and 1"
board.write("IgnoreDUTBusyW",3)
print("Ignore veto on DUT 0 and 1")
board.write("IgnoreDUTBusyW", 3)
IgnoreDUTBusy = board.read("IgnoreDUTBusyR")
print "IgnoreDUTBusyR = " , IgnoreDUTBusy
print("IgnoreDUTBusyR = ", IgnoreDUTBusy)
print "Turning off software trigger veto"
board.write("TriggerVetoW",0)
print("Turning off software trigger veto")
board.write("TriggerVetoW", 0)
print "Reseting FIFO"
board.write("EventFifoCSR",0x2)
print("Reseting FIFO")
board.write("EventFifoCSR", 0x2)
eventFifoFillLevel = board.read("EventFifoFillLevel")
print "FIFO fill level after resetting FIFO = " , eventFifoFillLevel
print("FIFO fill level after resetting FIFO = ", eventFifoFillLevel)
print "Enabling data recording"
board.write("Enable_Record_Data",1)
print("Enabling data recording")
board.write("Enable_Record_Data", 1)
#print "Enabling handshake: No-handshake"
#board.write("HandshakeTypeW",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
print("Setting internal trigger interval to ", TriggerInterval)
# 0->Internal pulse generator disabled. Any other value will generate pulses with a frequency of n*6.25ns
board.write("InternalTriggerIntervalW", TriggerInterval)
trigInterval = board.read("InternalTriggerIntervalR")
print "Trigger interval read back as ", trigInterval
print("Trigger interval read back as ", trigInterval)
print "Setting TPix_maskexternal to ignore external shutter and T0"
board.write("TPix_maskexternal",0x0003)
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):
for iLoop in range(0, numLoops):
board.write("TPix_T0", 0x0001)
......
# -*- coding: utf-8 -*-
import uhal
from I2CuHal import I2CCore
import StringIO
import io
class AD5665R:
#Class to configure the DAC modules
# 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
mystop = True
if intRef:
cmdDAC= [0x38,0x00,0x01]
cmdDAC = [0x38, 0x00, 0x01]
else:
cmdDAC= [0x38,0x00,0x00]
self.i2c.write( self.slaveaddr, cmdDAC, mystop)
cmdDAC = [0x38, 0x00, 0x00]
self.i2c.write(self.slaveaddr, cmdDAC, mystop)
if verbose:
print " AD5665R"
print "\tDAC int ref:", intRef
print(" AD5665R")
print("\tDAC 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)"
# 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)
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 StringIO
import io
import math
class ADN2814ACPZ:
#Class to configure the ADN2814 clock and data recovery chip (CDR)
# Class to configure the ADN2814 clock and data recovery chip (CDR)
# The I2C address can either be 0x40 or 0x60
def __init__(self, i2c, slaveaddr=0x40):
self.i2c = i2c
self.slaveaddr = slaveaddr
self.regDictionary= {'freq0': 0x0, 'freq1': 0x1, 'freq2': 0x2, 'rate': 0x3, 'misc': 0x4, 'ctrla': 0x8, 'ctrlb': 0x9, 'ctrlc': 0x11}
self.regDictionary = {'freq0': 0x0, 'freq1': 0x1, 'freq2': 0x2,
'rate': 0x3, 'misc': 0x4, 'ctrla': 0x8, 'ctrlb': 0x9, 'ctrlc': 0x11}
def writeReg(self, regN, regContent, verbose=False):
#Basic functionality to write to register.
regContent= regContent & 0xFF
mystop=True
cmd= [regN, regContent]
self.i2c.write( self.slaveaddr, cmd, mystop)
# Basic functionality to write to register.
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.
mystop=False
self.i2c.write( self.slaveaddr, [regN], mystop)
res= self.i2c.read( self.slaveaddr, nwords)
# Basic functionality to read from register.
mystop = False
self.i2c.write(self.slaveaddr, [regN], mystop)
res = self.i2c.read(self.slaveaddr, nwords)
return res
def readf0(self, verbose=False):
res= self.readReg(self.regDictionary['freq0'], 1, False)
res = self.readReg(self.regDictionary['freq0'], 1, False)
if verbose:
print "\tfreq0 is", res[0]
print("\tfreq0 is", res[0])
return res[0]
def readf1(self, verbose=False):
res= self.readReg(self.regDictionary['freq1'], 1, False)
res = self.readReg(self.regDictionary['freq1'], 1, False)
if verbose:
print "\tfreq1 is", res[0]
print("\tfreq1 is", res[0])
return res[0]
def readf2(self, verbose=False):
res= self.readReg(self.regDictionary['freq2'], 1, False)
res = self.readReg(self.regDictionary['freq2'], 1, False)
if verbose:
print "\tfreq2 is", res[0]
print("\tfreq2 is", res[0])
return res[0]
def readFrequency(self, verbose=False):
......@@ -59,86 +60,87 @@ class ADN2814ACPZ:
# return the status of the LOL bit MISC[3] and the STATIC LOL MISC[4]
# the STATIC LOL is asserted if a LOL condition occurred and remains asserted
# until cleared by writing 1 followed by 0 to the CTRLB[6] bit
misc= self.readReg(self.regDictionary['misc'], 1, False)[0]
staticLOL= (misc & 0x10000) >> 4
LOL= (misc & 0x1000) >> 3
misc = self.readReg(self.regDictionary['misc'], 1, False)[0]
staticLOL = (misc & 0x10000) >> 4
LOL = (misc & 0x1000) >> 3
if verbose:
print "MISC=", misc, "LOL=", LOL, "StaticLOL=", staticLOL
print("MISC=", misc, "LOL=", LOL, "StaticLOL=", staticLOL)
return [LOL, staticLOL]
def readRate(self, verbose=False):
rate_msb= self.readReg(self.regDictionary['rate'], 1, False)[0]
rate_lsb= self.readReg(self.regDictionary['misc'], 1, False)[0]
rate_lsb= 0x1 & rate_lsb
rate= (rate_msb << 1) | rate_lsb
rate_msb = self.readReg(self.regDictionary['rate'], 1, False)[0]
rate_lsb = self.readReg(self.regDictionary['misc'], 1, False)[0]
rate_lsb = 0x1 & rate_lsb
rate = (rate_msb << 1) | rate_lsb
if verbose:
print "\tcoarse rate is", rate
print("\tcoarse rate is", rate)
return rate
def _writeCTRLA(self, fRef, dataRatio, measureDataRate, lockToRef, verbose=False):
#write content to register CTRLA:
# write content to register CTRLA:
# fRef: reference frequency in MHz; range is [10 : 160]
# dataRatio: integer in range [0 : 8] equal to Data Rate/Div_FREF Ratio
# measureDataRate: set to 1 to measure data rate
# lockToRef= 0 > lock to input data; 1 > lock to reference clock
regContent= 0x0
regContent = 0x0
if fRef < 10:
print "fRef must be comprised between 10 and 160. Coherced to 10"
print("fRef must be comprised between 10 and 160. Coherced to 10")
fRef = 10
if fRef > 160:
print "fRef must be comprised between 10 and 160. Coherced to 160"
print("fRef must be comprised between 10 and 160. Coherced to 160")
fRef = 160
fRefRange={
10<= fRef <20 : 0x00,
20<= fRef <40 : 0x01,
40<= fRef <80 : 0x02,
80<= fRef <=160 : 0x03,
}[1]
fRefRange= fRefRange << 6
regContent= regContent | fRefRange
if ((1 <= dataRatio <= 256) & (isinstance(dataRatio, (int, long) )) ):
ratioValue= math.log(dataRatio, 2)
ratioValue= int(ratioValue)
fRefRange = {
10 <= fRef < 20: 0x00,
20 <= fRef < 40: 0x01,
40 <= fRef < 80: 0x02,
80 <= fRef <= 160: 0x03,
}[1]
fRefRange = fRefRange << 6
regContent = regContent | fRefRange
if ((1 <= dataRatio <= 256) & (isinstance(dataRatio, int))):
ratioValue = math.log(dataRatio, 2)
ratioValue = int(ratioValue)
else:
print " dataRatio should be an integer in the form 2^n with 0<= n <= 8. Coherced to 0"
ratioValue= 0
print(
" dataRatio should be an integer in the form 2^n with 0<= n <= 8. Coherced to 0")
ratioValue = 0
if verbose:
print "\tratioValue=", ratioValue
print("\tratioValue=", ratioValue)
ratioValue = ratioValue << 2
regContent= regContent | ratioValue
regContent = regContent | ratioValue
measureDataRate= (measureDataRate & 0x1) << 1
lockToRef= lockToRef & 0x1
regContent= regContent | measureDataRate | lockToRef
measureDataRate = (measureDataRate & 0x1) << 1
lockToRef = lockToRef & 0x1
regContent = regContent | measureDataRate | lockToRef
self.writeReg( self.regDictionary['ctrla'], regContent, verbose=False)
self.writeReg(self.regDictionary['ctrla'], regContent, verbose=False)
return
def _writeCTRLB(self, confLOL, rstMisc4, systemReset, rstMisc2, verbose=False):
#write content to register CTRLB:
# write content to register CTRLB:
# confLOL=0 > LOL pin normal operation; 1 > LOL pin is static LOL
# rstMisc4= Write a 1 followed by 0 to reset MISC[4] (staticLOL)
# systemReset= Write 1 followed by 0 to reset ADN2814
# rsttMisc2= Write a 1 followed by 0 to reset MISC[2] (data read measure complete)
regContent= 0x0
confLOL= (confLOL & 0x1) << 7
rstMisc4= (rstMisc4 & 0x1) << 6
systemReset= (systemReset & 0x1) << 5
rstMisc2= (rstMisc2 & 0x1) << 3
regContent= regContent | confLOL | rstMisc4 | systemReset | rstMisc2
self.writeReg( self.regDictionary['ctrlb'], regContent, verbose=False)
regContent = 0x0
confLOL = (confLOL & 0x1) << 7
rstMisc4 = (rstMisc4 & 0x1) << 6
systemReset = (systemReset & 0x1) << 5
rstMisc2 = (rstMisc2 & 0x1) << 3
regContent = regContent | confLOL | rstMisc4 | systemReset | rstMisc2
self.writeReg(self.regDictionary['ctrlb'], regContent, verbose=False)
return
def _writeCTRLC(self, confLOS, squelch, outBoost, verbose=False):
#write content to register CTRLC:
# write content to register CTRLC:
# confLOS= 0 > active high LOS; 1 > active low LOS
# squelch= 0 > squelch CLK and DATA; 1 > squelch CLK or DATA
# outBoost= 0 > default swing; boost output swing
regContent= 0x0
confLOS= (confLOS & 0x1) << 2
squelch= (squelch & 0x1) << 1
outBoost= (outBoost & 0x1)
regContent= regContent | confLOS | squelch | outBoost
self.writeReg( self.regDictionary['ctrlc'], regContent, verbose=False)
regContent = 0x0
confLOS = (confLOS & 0x1) << 2
squelch = (squelch & 0x1) << 1
outBoost = (outBoost & 0x1)
regContent = regContent | confLOS | squelch | outBoost
self.writeReg(self.regDictionary['ctrlc'], regContent, verbose=False)
return
# -*- coding: utf-8 -*-
import uhal
from I2CuHal import I2CCore
import StringIO
import io
import numpy as np
class ATSHA204A:
#Class for Atmel ATSHA204A eeprom
# Class for Atmel ATSHA204A eeprom
def __init__(self, i2c, slaveaddr= 0x64):
def __init__(self, i2c, slaveaddr=0x64):
self.i2c = i2c
self.slaveaddr = slaveaddr
#Slot size, in bytes.
self.SLOT_SIZE_BYTES = 32;
#Word size, in bytes. This is the base unit for all reads and writes.
self.WORD_SIZE_BYTES = 4;
#Maximum word offset per slot
self.MAX_WORD_OFFSET = 7;
#Size of the configuration zone, in bytes
self.CONFIGURATION_ZONE_SIZE_BYTES = 88;
#Number of slots in the configuration zone
self.CONFIGURATION_ZONE_SIZE_SLOTS = 3;
#Slot 3 in the configuration zone is only 24 bytes rather than 32, so the max word offset is limited to 5.
self.CONFIGURATION_ZONE_SLOT_2_MAX_WORD_OFFSET = 5;
#Size of the OTP zone, in bytes
self.OTP_ZONE_SIZE_BYTES = 64;
#Number of slots in the OTP zone
self.OTP_ZONE_SIZE_SLOTS = 2;
#Size of the data zone, in bytes
self.DATA_ZONE_SIZE_BYTES = 512;
#Number of slots in the data zone
self.DATA_ZONE_SIZE_SLOTS = 16;
#The data slot used for module configuration data
self.DATA_ZONE_SLOT_MODULE_CONFIGURATION = 0;
#Byte index of the OTP mode byte within its configuration word.
self.OTP_MODE_WORD_BYTE_INDEX = 2;
# Slot size, in bytes.
self.SLOT_SIZE_BYTES = 32
# Word size, in bytes. This is the base unit for all reads and writes.
self.WORD_SIZE_BYTES = 4
# Maximum word offset per slot
self.MAX_WORD_OFFSET = 7
# Size of the configuration zone, in bytes
self.CONFIGURATION_ZONE_SIZE_BYTES = 88
# Number of slots in the configuration zone
self.CONFIGURATION_ZONE_SIZE_SLOTS = 3
# Slot 3 in the configuration zone is only 24 bytes rather than 32, so the max word offset is limited to 5.
self.CONFIGURATION_ZONE_SLOT_2_MAX_WORD_OFFSET = 5
# Size of the OTP zone, in bytes
self.OTP_ZONE_SIZE_BYTES = 64
# Number of slots in the OTP zone
self.OTP_ZONE_SIZE_SLOTS = 2
# Size of the data zone, in bytes
self.DATA_ZONE_SIZE_BYTES = 512
# Number of slots in the data zone
self.DATA_ZONE_SIZE_SLOTS = 16
# The data slot used for module configuration data
self.DATA_ZONE_SLOT_MODULE_CONFIGURATION = 0
# Byte index of the OTP mode byte within its configuration word.
self.OTP_MODE_WORD_BYTE_INDEX = 2
#-------------------------------------------------------------------------------------------------
# -------------------------------------------------------------------------------------------------
# Command packets and I/O
#-------------------------------------------------------------------------------------------------
#Command execution status response block size
self.STATUS_RESPONSE_BLOCK_SIZE_BYTES = 4;
#Byte index of count in response block
self.STATUS_RESPONSE_COUNT_BYTE_INDEX = 0;
#Byte index of status code in response block
self.STATUS_RESPONSE_STATUS_BYTE_INDEX = 1;
#Checksum size
self.CHECKSUM_LENGTH_BYTES = 2;
#Index of the count byte in a command packet
self.COMMAND_PACKET_COUNT_BYTE_INDEX = 0;
#Size of count in a command packet
self.COMMAND_PACKET_COUNT_SIZE_BYTES = 1;
#Index of the opcode byte in a command packet
self.COMMAND_PACKET_OPCODE_BYTE_INDEX = 1;
#Size of the opcode byte in a command packet
self.COMMAND_PACKET_OPCODE_LENGTH_BYTES = 1;
#Index of param 1 in a command packet
self.COMMAND_PACKET_PARAM1_BYTE_INDEX = 2;
#Size of param 1 in a command packet
self.COMMAND_PACKET_PARAM1_SIZE_BYTES = 1;
#Index of param 2 in a command packet
self.COMMAND_PACKET_PARAM2_BYTE_INDEX = 3;
#Size of param 2 in a command packet
self.COMMAND_PACKET_PARAM2_SIZE_BYTES = 2;
# -------------------------------------------------------------------------------------------------
# Command execution status response block size
self.STATUS_RESPONSE_BLOCK_SIZE_BYTES = 4
# Byte index of count in response block
self.STATUS_RESPONSE_COUNT_BYTE_INDEX = 0
# Byte index of status code in response block
self.STATUS_RESPONSE_STATUS_BYTE_INDEX = 1
# Checksum size
self.CHECKSUM_LENGTH_BYTES = 2
# Index of the count byte in a command packet
self.COMMAND_PACKET_COUNT_BYTE_INDEX = 0
# Size of count in a command packet
self.COMMAND_PACKET_COUNT_SIZE_BYTES = 1
# Index of the opcode byte in a command packet
self.COMMAND_PACKET_OPCODE_BYTE_INDEX = 1
# Size of the opcode byte in a command packet
self.COMMAND_PACKET_OPCODE_LENGTH_BYTES = 1
# Index of param 1 in a command packet
self.COMMAND_PACKET_PARAM1_BYTE_INDEX = 2
# Size of param 1 in a command packet
self.COMMAND_PACKET_PARAM1_SIZE_BYTES = 1
# Index of param 2 in a command packet
self.COMMAND_PACKET_PARAM2_BYTE_INDEX = 3
# Size of param 2 in a command packet
self.COMMAND_PACKET_PARAM2_SIZE_BYTES = 2
def _CalculateCrc(self, pData, dataLengthBytes):
# Calculate a CRC-16 used when communicating with the device. Code taken from Atmel's library.
#The Atmel documentation only specifies that the CRC algorithm used on the ATSHA204A is CRC-16 with polynomial
#0x8005; compared to a standard CRC-16, however, the used algorithm doesn't use remainder reflection.
#@param pData The data to calculate the CRC for
#@param dataLengthBytes The number of bytes to process
#@return The CRC
# The Atmel documentation only specifies that the CRC algorithm used on the ATSHA204A is CRC-16 with polynomial
# 0x8005; compared to a standard CRC-16, however, the used algorithm doesn't use remainder reflection.
# @param pData The data to calculate the CRC for
# @param dataLengthBytes The number of bytes to process
# @return The CRC
polynomial = 0x8005
crcRegister = 0
if not pData:
print "_CalculateCrc: No data to process"
print("_CalculateCrc: No data to process")
return 0
for counter in range(0, dataLengthBytes):
shiftRegister= 0x01
shiftRegister = 0x01
for iShift in range(0, 8):
if (pData[counter] & shiftRegister) :
dataBit= 1
if (pData[counter] & shiftRegister):
dataBit = 1
else:
dataBit=0
crcBit= ((crcRegister) >> 15)
dataBit = 0
crcBit = ((crcRegister) >> 15)
crcRegister <<= 1
crcRegister= crcRegister & 0xffff
#print shiftRegister, "\t", dataBit, "\t", crcBit, "\t", crcRegister
shiftRegister= shiftRegister << 1
crcRegister = crcRegister & 0xffff
# print shiftRegister, "\t", dataBit, "\t", crcBit, "\t", crcRegister
shiftRegister = shiftRegister << 1
if (dataBit != crcBit):
#print "poly"
crcRegister ^= polynomial;
# print "poly"
crcRegister ^= polynomial
return crcRegister
def _wake(self, verifyDeviceIsAtmelAtsha204a, debug):
dummyWriteData = 0x00
mystop=True
self.i2c.write( self.slaveaddr, [dummyWriteData], mystop)
mystop = True
self.i2c.write(self.slaveaddr, [dummyWriteData], mystop)
if (verifyDeviceIsAtmelAtsha204a):
expectedStatusBlock= [ 0x04, 0x11, 0x33, 0x43 ];
nwords= 4
res= self.i2c.read( self.slaveaddr, nwords)
expectedStatusBlock = [0x04, 0x11, 0x33, 0x43]
nwords = 4
res = self.i2c.read(self.slaveaddr, nwords)
if (res != expectedStatusBlock):
print "Attempt to awake Atmel ATSHA204A failed"
print res
print("Attempt to awake Atmel ATSHA204A failed")
print(res)
def _GetCommandPacketSize(self, additionalDataLengthBytes):
packetSizeBytes = self.COMMAND_PACKET_COUNT_SIZE_BYTES + self.COMMAND_PACKET_OPCODE_LENGTH_BYTES \
+ self.COMMAND_PACKET_PARAM1_SIZE_BYTES + self.COMMAND_PACKET_PARAM2_SIZE_BYTES \
+ additionalDataLengthBytes + self.CHECKSUM_LENGTH_BYTES;
+ self.COMMAND_PACKET_PARAM1_SIZE_BYTES + self.COMMAND_PACKET_PARAM2_SIZE_BYTES \
+ additionalDataLengthBytes + self.CHECKSUM_LENGTH_BYTES
return packetSizeBytes
# -*- coding: utf-8 -*-
import uhal
from I2CuHal import I2CCore
import StringIO
import io
class E24AA025E48T:
#Class to configure the EEPROM
# 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)
# 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
......@@ -6,35 +6,34 @@ from RawI2cAccess import *
class FmcTluI2c:
############################
### configure i2c connection
# configure i2c connection
############################
def __init__(self,board):
def __init__(self, board):
self.board = board
i2cClockPrescale = 0x30
self.i2cBusProps = I2cBusProperties(self.board, i2cClockPrescale)
return
##########################
### scan all i2c addresses
# scan all i2c addresses
##########################
def i2c_scan(self):
list=[]
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)"
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+="(???)"
device += "(???)"
pass
list.append(device)
pass
......@@ -43,90 +42,88 @@ class FmcTluI2c:
pass
return list
###################
### write to EEPROM
# 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"
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"
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.
prom.write([address, value])
# write cycle time is 5ms. let's wait 10 to make sure.
time.sleep(0.01)
return
####################
### read from EEPROM
# 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"
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
# read serial number
######################
def get_serial_number(self):
result=""
result = ""
for iaddr in [0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff]:
result+="%02x "%(self.eeprom_read(iaddr))
result += "%02x " % (self.eeprom_read(iaddr))
pass
return result
#################
### set DAC value
# 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)"
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"
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)
# 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])
print("Turning internal reference ON")
dac.write([0x38, 0x00, 0x01])
else:
print "Turning internal reference OFF"
dac.write([0x38,0x00,0x00])
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
sequence = [(0x18 + (channel & 0x7)), (value/256) & 0xff, value & 0xff]
print(sequence)
dac.write(sequence)
##################################################
### convert required threshold voltage to DAC code
# convert required threshold voltage to DAC code
##################################################
def convert_voltage_to_dac(self, desiredVoltage, Vref=1.300):
Vdaq = ( desiredVoltage + Vref ) / 2
Vdaq = (desiredVoltage + Vref) / 2
dacCode = 0xFFFF * Vdaq / Vref
return int(dacCode)
##################################################
### calculate the DAC code required and set DAC
# calculate the DAC code required and set DAC
##################################################
def set_threshold_voltage(self, channel , voltage ):
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)
print(" requested voltage, calculated DAC code = ", voltage, dacCode)
self.set_dac(channel, dacCode)
This diff is collapsed.
......@@ -10,7 +10,6 @@ import uhal
verbose = True
################################################################################
# /*
# I2C CORE
......@@ -18,8 +17,6 @@ verbose = True
################################################################################
class I2CCore:
"""I2C communication block."""
......@@ -64,24 +61,24 @@ class I2CCore:
val = status[reg]
bval = bin(int(val))
if verbose:
print "\treg %s = %d, 0x%x, %s" % (reg, val, val, bval)
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
# INITIALIZATION OF THE I2S MASTER CORE
# Disable core
self.ctrl.write(0x0 << 7)
self.target.dispatch()
#Write pre-scale register
# Write pre-scale register
#prescale = int(self.wishboneclock / (5.0 * self.i2cclock)) - 1
#prescale = int(self.wishboneclock / (5.0 * self.i2cclock))
prescale = 0x0100 #FOR NOW HARDWIRED, TO BE MODIFIED
#prescale = int(self.wishboneclock / (5.0 * self.i2cclock))
prescale = 0x0100 # FOR NOW HARDWIRED, TO BE MODIFIED
self.prescale_low.write(prescale & 0xff)
self.prescale_high.write((prescale & 0xff00) >> 8)
#Enable core
# Enable core
self.ctrl.write(0x1 << 7)
self.target.dispatch()
......@@ -101,7 +98,7 @@ class I2CCore:
ack = self.checkack()
else:
time.sleep(self.delay)
ack = self.checkack()#Remove this?
ack = self.checkack() # Remove this?
return ack
################################################################################
......@@ -110,8 +107,6 @@ class I2CCore:
# */
################################################################################
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)
......@@ -121,23 +116,23 @@ class I2CCore:
startcmd = 0x1 << 7
stopcmd = 0x1 << 6
writecmd = 0x1 << 4
#Set transmit register (write operation, LSB=0)
# Set transmit register (write operation, LSB=0)
self.data.write(addr)
#Set Command Register to 0x90 (write, start)
# 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()
print "no ack from I2C address", hex(addr>>1)
print("no ack from I2C address", hex(addr >> 1))
return nwritten
nwritten += 1
for val in data:
val &= 0xff
#Write slave memory address
# Write slave memory address
self.data.write(val)
#Set Command Register to 0x10 (write)
# Set Command Register to 0x10 (write)
self.cmd_stat.write(I2CCore.writecmd)
self.target.dispatch()
ack = self.delayorcheckack()
......@@ -162,7 +157,7 @@ class I2CCore:
data = []
addr &= 0x7f
addr = addr << 1
addr |= 0x1 # read bit
addr |= 0x1 # read bit
self.data.write(addr)
self.cmd_stat.write(I2CCore.startcmd | I2CCore.writecmd)
self.target.dispatch()
......@@ -173,16 +168,18 @@ class I2CCore:
return data
for i in range(n):
if i < (n-1):
self.cmd_stat.write(I2CCore.readcmd) # <---
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()
# <--- This tells the slave that it is the last word
self.cmd_stat.write(
I2CCore.readcmd | I2CCore.ack | I2CCore.stopcmd)
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()
# self.cmd_stat.write(I2CCore.stopcmd)
# self.target.dispatch()
return data
################################################################################
......@@ -192,7 +189,6 @@ class I2CCore:
################################################################################
# def writeread(self, addr, data, n):
# """Write data to device, then read n bytes back from it."""
# nwritten = self.write(addr, data, stop=False)
......@@ -200,7 +196,6 @@ class I2CCore:
# if nwritten == len(data):
# readdata = self.read(addr, n)
# return nwritten, readdata
"""
SPI core XML:
......@@ -214,13 +209,14 @@ SPI core XML:
<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
......@@ -238,20 +234,21 @@ class SPICore:
"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
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
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
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
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))
print("SPI control val = 0x%x = %s" %
(self.control_val, bin(self.control_val)))
self.configured = True
def transmit(self, chip, value):
......@@ -278,5 +275,5 @@ class SPICore:
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)
# print "Received data: 0x%x, status = 0x%x, ss = 0x%x" % (data, status, ss)
return data
......@@ -10,15 +10,14 @@ import uhal
verbose = True
################################################################################
# /*
# I2C CORE
# */
################################################################################
### Same as the class defined in I2CuHal.py but the register names are changed to
### comply with D. Newbold's notation. To be used in the Dune SFP Fanout (pc059a)
# Same as the class defined in I2CuHal.py but the register names are changed to
# comply with D. Newbold's notation. To be used in the Dune SFP Fanout (pc059a)
class I2CCore:
"""I2C communication block."""
......@@ -64,24 +63,24 @@ class I2CCore:
val = status[reg]
bval = bin(int(val))
if verbose:
print "\treg %s = %d, 0x%x, %s" % (reg, val, val, bval)
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
# INITIALIZATION OF THE I2S MASTER CORE
# Disable core
self.ctrl.write(0x0 << 7)
self.target.dispatch()
#Write pre-scale register
# Write pre-scale register
#prescale = int(self.wishboneclock / (5.0 * self.i2cclock)) - 1
#prescale = int(self.wishboneclock / (5.0 * self.i2cclock))
prescale = 0x0100 #FOR NOW HARDWIRED, TO BE MODIFIED
prescale = 0x0100 # FOR NOW HARDWIRED, TO BE MODIFIED
self.prescale_low.write(prescale & 0xff)
self.prescale_high.write((prescale & 0xff00) >> 8)
#Enable core
# Enable core
self.ctrl.write(0x1 << 7)
self.target.dispatch()
......@@ -101,7 +100,7 @@ class I2CCore:
ack = self.checkack()
else:
time.sleep(self.delay)
ack = self.checkack()#Remove this?
ack = self.checkack() # Remove this?
return ack
################################################################################
......@@ -110,8 +109,6 @@ class I2CCore:
# */
################################################################################
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)
......@@ -121,23 +118,23 @@ class I2CCore:
startcmd = 0x1 << 7
stopcmd = 0x1 << 6
writecmd = 0x1 << 4
#Set transmit register (write operation, LSB=0)
# Set transmit register (write operation, LSB=0)
self.data.write(addr)
#Set Command Register to 0x90 (write, start)
# 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()
print "no ack from I2C address", hex(addr>>1)
print("no ack from I2C address", hex(addr >> 1))
return nwritten
nwritten += 1
for val in data:
val &= 0xff
#Write slave memory address
# Write slave memory address
self.data.write(val)
#Set Command Register to 0x10 (write)
# Set Command Register to 0x10 (write)
self.cmd_stat.write(I2CCore.writecmd)
self.target.dispatch()
ack = self.delayorcheckack()
......@@ -162,7 +159,7 @@ class I2CCore:
data = []
addr &= 0x7f
addr = addr << 1
addr |= 0x1 # read bit
addr |= 0x1 # read bit
self.data.write(addr)
self.cmd_stat.write(I2CCore.startcmd | I2CCore.writecmd)
self.target.dispatch()
......@@ -173,16 +170,18 @@ class I2CCore:
return data
for i in range(n):
if i < (n-1):
self.cmd_stat.write(I2CCore.readcmd) # <---
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()
# <--- This tells the slave that it is the last word
self.cmd_stat.write(
I2CCore.readcmd | I2CCore.ack | I2CCore.stopcmd)
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()
# self.cmd_stat.write(I2CCore.stopcmd)
# self.target.dispatch()
return data
################################################################################
......@@ -192,7 +191,6 @@ class I2CCore:
################################################################################
# def writeread(self, addr, data, n):
# """Write data to device, then read n bytes back from it."""
# nwritten = self.write(addr, data, stop=False)
......@@ -200,7 +198,6 @@ class I2CCore:
# if nwritten == len(data):
# readdata = self.read(addr, n)
# return nwritten, readdata
"""
SPI core XML:
......@@ -214,13 +211,14 @@ SPI core XML:
<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
......@@ -238,20 +236,21 @@ class SPICore:
"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
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
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
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
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))
print("SPI control val = 0x%x = %s" %
(self.control_val, bin(self.control_val)))
self.configured = True
def transmit(self, chip, value):
......@@ -278,5 +277,5 @@ class SPICore:
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)
# print "Received data: 0x%x, status = 0x%x, ss = 0x%x" % (data, status, ss)
return data
......@@ -9,20 +9,20 @@
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.
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
......@@ -34,7 +34,7 @@ class I2cBusProperties(object):
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
......@@ -44,45 +44,44 @@ class I2cBusProperties(object):
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"):
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".
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
......@@ -91,30 +90,36 @@ class I2cBusProperties(object):
object.__init__(self)
self.chipsBus = chipsBusDevice
self.preHiVal = ((clkPrescaleU16 & 0xff00) >> 8)
self.preLoVal = (clkPrescaleU16 & 0xff)
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]
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!")
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]
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!")
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]
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!")
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.preLoReg = clkPrescaleLoByteReg
self.ctrlReg = controlReg
self.txReg = transmitReg
self.rxReg = receiveReg
......
# -*- coding: utf-8 -*-
import uhal
from I2CuHal import I2CCore
import StringIO
import io
class NHDC0220Biz:
#Class to configure the EEPROM
# Class to configure the EEPROM
def __init__(self, i2c, slaveaddr=0x3c):
self.i2c = i2c
self.slaveaddr = 0x2a#slaveaddr
self.slaveaddr = 0x2a # slaveaddr
def test(self):
print "Testing the display"
return
print("Testing the display")
return
def writeSomething(self):
mystop= True
print "Write random stuff"
myaddr= [0x08, 0x38]
self.i2c.write( self.slaveaddr, myaddr, mystop)
return
mystop = True
print("Write random stuff")
myaddr = [0x08, 0x38]
self.i2c.write(self.slaveaddr, myaddr, mystop)
return
# -*- coding: utf-8 -*-
import uhal
from I2CuHal import I2CCore
import StringIO
import io
class PCA9539PW:
#Class to configure the expander modules
# 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.
# Basic functionality to write to register.
if (regN < 0) | (regN > 7):
print "PCA9539PW - ERROR: register number should be in range [0: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)
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.
# Basic functionality to read from register.
if (regN < 0) | (regN > 7):
print "PCA9539PW - ERROR: register number should be in range [0: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)
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).
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"
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).
# 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"
print("PCA9539PW - ERROR: regN should be 0 or 1")
return
res= self.readReg(regN+4, 1)
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).
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"
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).
# 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"
print("PCA9539PW - ERROR: regN should be 0 or 1")
return
res= self.readReg(regN+6, 1)
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.
# 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"
print("PCA9539PW - ERROR: bank should be 0 or 1")
return
res= self.readReg(bank, 1)
res = self.readReg(bank, 1)
return res
def setOutputs(self, bank, values= 0x00):
#Set the content of the output flip-flops.
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"
print("PCA9539PW - ERROR: bank should be 0 or 1")
return
values = values & 0xFF
self.writeReg(bank+2, values)
def getOutputs(self, bank):
#Read the state of the outputs (i.e. what value is being written to them)
# Read the state of the outputs (i.e. what value is being written to them)
if (bank < 0) | (bank > 1):
print "PCA9539PW - ERROR: bank should be 0 or 1"
print("PCA9539PW - ERROR: bank should be 0 or 1")
return
res= self.readReg(bank+2, 1)
res = self.readReg(bank+2, 1)
return res
# -*- coding: utf-8 -*-
import uhal
from I2CuHal import I2CCore
import StringIO
import io
class PCA9548ADW:
#Class to configure the I2C multiplexer
# Class to configure the I2C multiplexer
def __init__(self, i2c, slaveaddr=0x74):
self.i2c = i2c
self.slaveaddr = slaveaddr
def disableAllChannels(self, verbose=False):
#Disable all channels so that none of the MUX outputs is visible
# Disable all channels so that none of the MUX outputs is visible
# to the upstream I2C bus
mystop=True
cmd= [0x0]
self.i2c.write( self.slaveaddr, cmd, mystop)
mystop = True
cmd = [0x0]
self.i2c.write(self.slaveaddr, cmd, mystop)
def getChannelStatus(self, verbose=False):
#Basic functionality to read the status of the control register and determine
# Basic functionality to read the status of the control register and determine
# which channel is currently enabled.
mystop=False
cmd= []
self.i2c.write( self.slaveaddr, cmd, mystop)
res= self.i2c.read( self.slaveaddr, 1)
mystop = False
cmd = []
self.i2c.write(self.slaveaddr, cmd, mystop)
res = self.i2c.read(self.slaveaddr, 1)
return res[0]
def setActiveChannel(self, channel, verbose=False):
#Basic functionality to activate one channel
# Basic functionality to activate one channel
# In principle multiple channels can be active at the same time (see
# function "setMultipleChannels")
if (channel < 0) | (channel > 7):
print "PCA9539PW - ERROR: channel number should be in range [0:7]"
print("PCA9539PW - ERROR: channel number should be in range [0:7]")
return
mystop=True
cmd= [0x1 << channel]
#print "\tChannel is ", channel, "we write ", cmd
self.i2c.write( self.slaveaddr, cmd, mystop)
mystop = True
cmd = [0x1 << channel]
# print "\tChannel is ", channel, "we write ", cmd
self.i2c.write(self.slaveaddr, cmd, mystop)
def setMultipleChannels(self, channels, verbose=False):
#Basic functionality to activate multiple channels
# Basic functionality to activate multiple channels
# channels is a byte: each bit set to one will set the corresponding channels
# as active. The slave connected to that channel will be visible on the I2C bus.
# NOTE: this can lead to address clashes!
channels = channels & 0xFF
mystop=True
cmd= [channels]
#print "\tChannel is ", channel, "we write ", cmd
self.i2c.write( self.slaveaddr, cmd, mystop)
mystop = True
cmd = [channels]
# print "\tChannel is ", channel, "we write ", cmd
self.i2c.write(self.slaveaddr, cmd, mystop)
......@@ -21,13 +21,12 @@ class RawI2cAccess:
# they differ from the defaults specified by the I2cBusProperties
# class).
#
#slaveAddr: The address of the I2C slave you wish to communicate with.
# 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
......@@ -40,7 +39,7 @@ class RawI2cAccess:
try:
self._chipsBus().queueWrite(self._i2cProps.ctrlReg, 0x00)
#self._chipsBus().getNode(self._i2cProps.ctrlReg).write(0)
# self._chipsBus().getNode(self._i2cProps.ctrlReg).write(0)
self._chipsBus().queueWrite(self._i2cProps.preHiReg,
self._i2cProps.preHiVal)
self._chipsBus().queueWrite(self._i2cProps.preLoReg,
......@@ -49,10 +48,9 @@ class RawI2cAccess:
self._chipsBus().queueWrite(self._i2cProps.txReg, 0x00)
self._chipsBus().queueWrite(self._i2cProps.cmdReg, 0x00)
self._chipsBus().queueRun()
except ChipsException, err:
except ChipsException as 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).
......@@ -62,11 +60,10 @@ class RawI2cAccess:
try:
result = self._privateRead(numBytes)
except ChipsException, err:
except ChipsException as err:
raise ChipsException("I2C read error:\n\t" + str(err))
return result
def write(self, listDataU8):
# Performs an 8-bit I2C write.
......@@ -76,11 +73,10 @@ class RawI2cAccess:
try:
self._privateWrite(listDataU8)
except ChipsException, err:
except ChipsException as err:
raise ChipsException("I2C write error:\n\t" + str(err))
return
def _chipsBus(self):
# Returns the instance of the ChipsBus device that's hosting
......@@ -88,7 +84,6 @@ class RawI2cAccess:
return self._i2cProps.chipsBus
def _privateRead(self, numBytes):
# I2C read implementation.
......@@ -96,7 +91,6 @@ class RawI2cAccess:
# 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
......@@ -127,31 +121,30 @@ class RawI2cAccess:
# Wait for transaction to finish.
self._i2cWaitUntilFinished()
result=[]
result = []
for ibyte in range(numBytes):
if ibyte==numBytes-1:
stop_bit=0x40
ack_bit=0x08
if ibyte == numBytes-1:
stop_bit = 0x40
ack_bit = 0x08
else:
stop_bit=0
ack_bit=0
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)
self._i2cWaitUntilFinished(requireAcknowledgement=False,
requireBusIdleAtEnd=True)
else:
self._i2cWaitUntilFinished(requireAcknowledgement = False,
requireBusIdleAtEnd = False)
self._i2cWaitUntilFinished(requireAcknowledgement=False,
requireBusIdleAtEnd=False)
pass
result.append(self._chipsBus().read(self._i2cProps.rxReg))
return result
def _privateWrite(self, listDataU8):
# I2C write implementation.
......@@ -189,10 +182,10 @@ class RawI2cAccess:
for ibyte in range(len(listDataU8)):
dataU8 = listDataU8[ibyte]
if ibyte==len(listDataU8)-1:
stop_bit=0x40
if ibyte == len(listDataU8)-1:
stop_bit = 0x40
else:
stop_bit=0x00
stop_bit = 0x00
pass
# Set data to be written in transmit reg
self._chipsBus().queueWrite(self._i2cProps.txReg, (dataU8 & 0xff))
......@@ -203,19 +196,18 @@ class RawI2cAccess:
# 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)
self._i2cWaitUntilFinished(requireAcknowledgement=True,
requireBusIdleAtEnd=True)
else:
self._i2cWaitUntilFinished(requireAcknowledgement = True,
requireBusIdleAtEnd = False)
self._i2cWaitUntilFinished(requireAcknowledgement=True,
requireBusIdleAtEnd=False)
pass
pass
return
def _i2cWaitUntilFinished(self, requireAcknowledgement = True,
requireBusIdleAtEnd = False):
def _i2cWaitUntilFinished(self, requireAcknowledgement=True,
requireBusIdleAtEnd=False):
# Ensures the current bus transaction has finished successfully
# before allowing further I2C bus transactions
......@@ -252,10 +244,12 @@ class RawI2cAccess:
# the bus operated as expected:
if attempt > maxRetry:
raise ChipsException("I2C error: Transaction timeout - the 'Transfer in Progress' bit remained high for too long!")
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!")
raise ChipsException(
"I2C error: Transfer finished but bus still busy!")
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
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