# fspi210.py tlfong01 2019dec17hkt1452
# ******************************************************************************************************
# *** Import ***
# ******************************************************************************************************
from time import sleep
import spidev
import os
import sys
from datetime import datetime
from signal import pause
import fprint171 as fprint
import fmnu205 as fmnu
# ******************************************************************************************************
# *** SPI Bus Config for ADXL345 Only ***
# ******************************************************************************************************
#initBusMode = 0b00 # default, for adxl355
initBusMode = 0b11 # for adxl345 only
initBusSpeed = 100000
spiBus00 = spidev.SpiDev()
spiBus00.open(0,0)
spiBus00.mode = initBusMode
spiBus00.max_speed_hz = initBusSpeed
spiBus01 = spidev.SpiDev()
spiBus01.open(0,1)
spiBus01.mode = initBusMode
spiBus01.max_speed_hz = initBusSpeed
spiBus10 = spidev.SpiDev()
spiBus10.open(1,0)
spiBus10.mode = initBusMode
spiBus10.max_speed_hz = initBusSpeed
#spiBus11 = spidev.SpiDev()
#spiBus11.open(1,1)
#spiBus11.mode = initBusMode
#spiBus11.max_speed_hz = initBusSpeed
#spiBus12 = spidev.SpiDev()
#spiBus12.open(1,2)
#spiBus12.mode = initBusMode
#spiBus12.max_speed_hz = initBusSpeed
spiBusDict = {
'SpiBus00': spiBus00,
'SpiBus01': spiBus01,
'SpiBus10': spiBus10,
#'SpiBus11': spiBus11,
#'SpiBus12': spiBus12,
}
spiControlByteDict = {
'TestByte0x5a' : 0x5a,
'TestByte0x5b' : 0x5b,
'TestByte0x5c' : 0x5c,
'TestByte0x5d' : 0x5d,
'TestByte0x5e' : 0x5e,
'TestByte0x55' : 0x55,
'TestByte0x66' : 0x66,
'RepeatTimes100' : 100,
'RepeatTimes1000' : 1000,
'RepeatTimes10000' : 10000,
'RepeatTimes1000000' : 1000000,
'RepeatTimes10000000' : 10000000,
'PauseMilliSeconds10' : 0.01,
}
# ******************************************************************************************************
# *** System Functions ***
# ******************************************************************************************************
def getSystemConfigInfo():
# *** General ***
print('*** General System Config ***')
os.system('date')
os.system('cat /etc/issue.net')
os.system('uname -a')
os.system('grep Model /proc/cpuinfo')
os.system('grep MemTotal /proc/meminfo')
# *** SPI ***
print('*** grep /boot/config.txt ***')
os.system('grep dtparam=spi /boot/config.txt')
os.system('grep dtoverlay=spi1-3cs /boot/config.txt')
print('*** $ ls /dev/spi* ***')
os.system('ls /dev/spi*')
# *** I2C***
print('*** grep I2c /boot/config.txt) ***')
os.system('grep dtparam=i2c /boot/config.txt')
print('*** I2C dtoverlay ***')
os.system('grep dtoverlay=i2c /boot/config.txt')
print('*** $ ls /dev/i2c* ***')
os.system('ls /dev/i2c*')
print('*** i2cdetect -y 1 ***')
os.system('i2cdetect -y 1')
print('*** i2cdetect -y 3 ***')
os.system('i2cdetect -y 3')
#os.system('i2cdetect -y 4') # Clashes with SPI1 CE1 !!!
#os.system('i2cdetect -y 5') # Not working !!!
#os.system('i2cdetect -y 6') # Not working !!!
print('*** End of System, SPI, and I2C Config Summary ***')
return
def setSpiPortSpeed(spiBus, busSpeed):
spiBus.max_speed_hz = busSpeed
return
def closeSpi(spi):
spiBus.close()
return
# ******************************************************************************************************
# *** SPI Send/Recv Functions ***
# ******************************************************************************************************
# *** SPI Send/Receive 1/2/3 Bytes ***
def spiSendRecvOneByte(spiBus, sendByte):
sendByteArray = [sendByte]
recvByteArray = spiBus.xfer2(sendByteArray)
return recvByteArray
def spiSendRecvTwoBytes(spiBus, sendByte1, sendByte2):
sendByteArray = [sendByte1, sendByte2]
recvByteArray = spiBus.xfer2(sendByteArray)
return recvByteArray
def spiSendRecvThreeBytes(spiBus, sendByte1, sendByte2, sendByte3):
sendByteArray = [sendByte1, sendByte2, sendByte3]
recvByteArray = spiBus.xfer2(sendByteArray)
return recvByteArray
# ******************************************************************************************************
# *** SPI Loopback Functions ***
# ******************************************************************************************************
def loopbackOneByte(spiBus, sendByte):
fprint.printBeginExecFunction()
recvByteArray = spiSendRecvOneByte(spiBus, sendByte)
recvByte = recvByteArray[0]
fprint.printTitleOneByteNum('sendByte', fprint.indentFormat640, sendByte)
fprint.printTitleOneByteNum('recvByte', fprint.indentFormat640, recvByte)
fprint.printEndExecFunction()
return
def loopbackTwoBytes(spiBus, sendByte1, sendByte2):
fprint.printBeginExecFunction()
recvByteArray = spiSendRecvTwoBytes(spiBus, sendByte1, sendByte2)
recvByte1 = recvByteArray[0]
recvByte2 = recvByteArray[1]
sendBytes = fprint.convertOneByteNumToFourCharStr(sendByte1) + ' ' + fprint.convertOneByteNumToFourCharStr(sendByte2)
fprint.printTitleString('sendBytes', fprint.indentFormat640, sendBytes)
recvBytes = fprint.convertOneByteNumToFourCharStr(recvByte1) + ' ' + fprint.convertOneByteNumToFourCharStr(recvByte2)
fprint.printTitleString('sendBytes', fprint.indentFormat640, recvBytes)
fprint.printEndExecFunction()
return
def loopbackThreeBytes(spiBus, sendByte1, sendByte2, sendByte3):
fprint.printBeginExecFunction()
recvByteArray = spiSendRecvThreeBytes(spiBus, sendByte1, sendByte2, sendByte3)
recvByte1 = recvByteArray[0]
recvByte2 = recvByteArray[1]
recvByte3 = recvByteArray[2]
sendBytes = fprint.convertOneByteNumToFourCharStr(sendByte1) + ' ' + fprint.convertOneByteNumToFourCharStr(sendByte2) + ' ' + \
fprint.convertOneByteNumToFourCharStr(sendByte3)
fprint.printTitleString('sendBytes', fprint.indentFormat640, sendBytes)
recvBytes = fprint.convertOneByteNumToFourCharStr(recvByte1) + ' ' + fprint.convertOneByteNumToFourCharStr(recvByte2) + ' ' + \
fprint.convertOneByteNumToFourCharStr(recvByte3)
fprint.printTitleString('sendBytes', fprint.indentFormat640, recvBytes)
fprint.printEndExecFunction()
return
# ******************************************************************************************************
# *** Test SPI Loopback 1/2/3 bytes ***
# ******************************************************************************************************
def testLoopBackOneByte(spiBusName, testByteName):
spiBus = spiBusDict[spiBusName]
testByte = spiControlByteDict[testByteName]
loopbackOneByte(spiBus, testByte)
return
def testLoopbackTwoBytes(spiBusName, testByteName1, testByteName2):
spiBus = spiBusDict[spiBusName]
testByte1 = spiControlByteDict[testByteName1]
testByte2 = spiControlByteDict[testByteName1]
loopbackTwoBytes(spiBus, testByte1, testByte2)
return
def testLoopbackThreeBytes(spiBusName, testByteName1, testByteName2, testByteName3):
spiBus = spiBusDict[spiBusName]
testByte1 = spiControlByteDict[testByteName1]
testByte2 = spiControlByteDict[testByteName2]
testByte3 = spiControlByteDict[testByteName3]
loopbackThreeBytes(spiBus, testByte1, testByte2, testByte3)
return
# ******************************************************************************************************
# *** Test SPI Loopback 1/2/3 bytes ***
# ******************************************************************************************************
def testRepeatSendOneByte(spiBusName, testByteName, repeatTimesName, pauseMilliSecondsName):
fprint.printBeginExecFunction()
spiBus = spiBusDict[spiBusName]
testByte = spiControlByteDict[testByteName]
repeatTimes = spiControlByteDict[repeatTimesName]
pauseMilliSeconds = spiControlByteDict[pauseMilliSecondsName]
for count in range(repeatTimes):
spiSendRecvOneByte(spiBus, testByte)
sleep(pauseMilliSeconds)
fprint.printEndExecFunction()
return
def testRepeatSendTwoBytes(spiBusName, testByteName1, testByteName2, repeatTimesName, pauseMilliSecondsName):
fprint.printBeginExecFunction()
spiBus = spiBusDict[spiBusName]
testByte1 = spiControlByteDict[testByteName1]
testByte2 = spiControlByteDict[testByteName2]
repeatTimes = spiControlByteDict[repeatTimesName]
pauseMilliSeconds = spiControlByteDict[pauseMilliSecondsName]
for count in range(repeatTimes):
spiSendRecvTwoBytes(spiBus, testByte1, testByte2)
sleep(pauseMilliSeconds)
fprint.printEndExecFunction()
return
def testRepeatSendThreeBytes(spiBusName, testByteName1, testByteName2, testByteName3, repeatTimesName, pauseMilliSecondsName):
fprint.printBeginExecFunction()
spiBus = spiBusDict[spiBusName]
testByte1 = spiControlByteDict[testByteName1]
testByte2 = spiControlByteDict[testByteName2]
testByte3 = spiControlByteDict[testByteName3]
repeatTimes = spiControlByteDict[repeatTimesName]
pauseMilliSeconds = spiControlByteDict[pauseMilliSecondsName]
for count in range(repeatTimes):
spiSendRecvThreeBytes(spiBus, testByte1, testByte2, testByte3)
sleep(pauseMilliSeconds)
fprint.printEndExecFunction()
return
# *** Read Device Reg ***
def writedDevRegOneByte(spiBusName, devRegAddrDict, devRegName, controlByteDict, writeByteName):
spiBus = spiBusDict[spiBusName]
devRegAddr = devRegAddrDict[devRegName]
writeDevRegAddr = devRegAddr | 0x00 # for Adxl345 only. For default = devRegaddr << 1
writeByte = controlByteDict[writeByteName]
spiSendRecvTwoBytes(spiBus, writeDevRegAddr, writeByte)
return
def readDevRegOneByte(spiBusName, devRegAddrDict, devRegName):
spiBus = spiBusDict[spiBusName]
devRegAddr = devRegAddrDict[devRegName]
readDevRegAddr = devRegAddr | 0x80 # for Adxl345 only. For default = (devRegaddr << 1) | 0x01
dummyByte = 0x00
recvByteArray = spiSendRecvTwoBytes(spiBus, readDevRegAddr, dummyByte)
readByte = recvByteArray[1]
return readByte
# ******************************************************************************************************
# *** Adxl345 Functions ***
# ******************************************************************************************************
adxl345RegAddrDict = {
'DevIdReg' : 0x00,
'DataFormatReg' : 0x31,
'PowerControlReg' : 0x2d,
'InterruptConfigReg' : 0x2e,
'DataX0' : 0x32,
'DataX1' : 0x33,
'DataY0' : 0x34,
'DataY1' : 0x35,
'DataZ0' : 0x36,
'DataZ1' : 0x37,
}
adxl345ControlByteDict = {
'DevIdByte' : 0xe5,
'Format16G13Bit' : 0x0B,
'StartMeasurement' : 0x08,
'InterruptDataReadyEnable' : 0x80,
'InterruptDataReadyDisable' : 0x00,
}
adxl345ModuleDict = {
'ModuleType' : 'ADXL345',
'ModuleHelp' : 'Adxl345AccelerometerHelp',
'RegAddrDict' : 'Adxl345RegAddrDict',
'ControlByteDict' : 'Adxl345ControlByteDict',
'DevIdRegName' : 'DevIdReg',
'DevIdByteName' : 'DevIdByte',
'Jacky' : {'SpiBusName' : 'SpiBus00',
},
'Katie' : {'SpiBusName' : 'SpiBus00',
},
'Lucy' : {'SpiBusName' : 'SpiBus10',
},
'Maggi' : {'SpiBusName' : 'SpiBus11',
},
'Nancy' : {'SpiBusName' : 'SpiBus12',
},
}
# *** Module Dict Dict ***
moduleDictDict = {
'Adxl345' : adxl345ModuleDict,
}
# *** Test ADXL345 Accelerometer ***
def adxl345ReadRegOneByte(deviceNickName, devRegName):
fprint.printBeginExecFunction()
moduleTypeName = 'Adxl345'
moduleDict = moduleDictDict['Adxl345']
spiBusName = moduleDict[deviceNickName]['SpiBusName']
devRegAddrDict = adxl345RegAddrDict
spiBus = spiBusDict[spiBusName]
devRegAddr = devRegAddrDict[devRegName]
readByte = readDevRegOneByte(spiBusName, devRegAddrDict, devRegName)
fprint.printTitleString('BusName', fprint.indentFormat640, spiBusName) # For debugging
fprint.printTitleString('DevIdRegName', fprint.indentFormat640, devRegName) # For debugging
fprint.printTitleOneByteNum('DevRegAddr', fprint.indentFormat640, devRegAddr) # For debugging
fprint.printTitleOneByteNum('DevReg Contents',fprint.indentFormat640, readByte) # For debugging
fprint.printEndExecFunction()
return readByte
def adxl345WriteReadRegOneByte(deviceNickName, devRegName, writeByteName):
fprint.printBeginExecFunction()
moduleTypeName = 'Adxl345'
moduleDict = moduleDictDict['Adxl345']
spiBusName = moduleDict[deviceNickName]['SpiBusName']
devRegAddrDict = adxl345RegAddrDict
controlByteDict = adxl345ControlByteDict
spiBus = spiBusDict[spiBusName]
devRegAddr = devRegAddrDict[devRegName]
writeByte = controlByteDict[writeByteName]
writedDevRegOneByte(spiBusName, devRegAddrDict, devRegName, controlByteDict, writeByteName)
readByte = readDevRegOneByte(spiBusName, devRegAddrDict, devRegName)
fprint.printTitleString('BusName', fprint.indentFormat640, spiBusName) # For debugging
fprint.printTitleString('DevIdRegName', fprint.indentFormat640, devRegName) # For debugging
fprint.printTitleOneByteNum('DevRegAddr', fprint.indentFormat640, devRegAddr) # For debugging
fprint.printTitleString('WriteByteName', fprint.indentFormat640, writeByteName) # For debugging
fprint.printTitleOneByteNum('WriteByte', fprint.indentFormat640, writeByte) # For debugging
fprint.printTitleOneByteNum('Read Back Byte', fprint.indentFormat640, readByte) # For debugging
fprint.printEndExecFunction()
return
# ******************************************************************************************************
# *** Adxl345 Test Functions ***
# ******************************************************************************************************
def checkDeviceId(deviceName):
readByte = adxl345ReadRegOneByte(deviceName, 'DevIdReg')
fprint.printTitleOneByteNum('DevIdRegister Contests =', fprint.indentFormat640, readByte)
return
def configDevice(deviceInckName):
# *** Config Adxl345 ***
adxl345WriteReadRegOneByte(deviceInckName, 'DataFormatReg', 'Format16G13Bit')
adxl345WriteReadRegOneByte(deviceInckName, 'InterruptConfigReg', 'InterruptDataReadyDisable')
return
def convertTwoCompNumToDecNum(twoCompNum, numBytes):
twoCompNumStr = bin(twoCompNum)
val = int(twoCompNumStr, numBytes)
b = val.to_bytes(numBytes, byteorder=sys.byteorder, signed = False)
decNum = int.from_bytes(b, byteorder = sys.byteorder, signed = True)
return decNum
def getXyzDecimalValuesList(deviceNickName):
# *** Read Two's Compliment Raw Results ***
x0 = adxl345ReadRegOneByte(deviceNickName, 'DataX0')
x1 = adxl345ReadRegOneByte(deviceNickName, 'DataX1')
y0 = adxl345ReadRegOneByte(deviceNickName, 'DataY0')
y1 = adxl345ReadRegOneByte(deviceNickName, 'DataY1')
z0 = adxl345ReadRegOneByte(deviceNickName, 'DataZ0')
z1 = adxl345ReadRegOneByte(deviceNickName, 'DataZ1')
# *** Convert To Decimal Results List ***
xTwoComp = (x1 << 8) | x0
yTwoComp = (y1 << 8) | y0
zTwoComp = (z1 << 8) | z0
xDecNum = convertTwoCompNumToDecNum(xTwoComp, 2)
yDecNum = convertTwoCompNumToDecNum(yTwoComp, 2)
zDecNum = convertTwoCompNumToDecNum(zTwoComp, 2)
xyzDecimalValuesList = (xDecNum, yDecNum, zDecNum)
return xyzDecimalValuesList
def getRepeatMeasurementResultsList(deviceNickName, repeatTimes, pauseSeconds):
outputListStrList = ['dummy', 'dummy', 'dummy', 'dummy']
count = 0
for count in range(repeatTimes):
# *** Start Measurement ***
adxl345WriteReadRegOneByte(deviceNickName, 'PowerControlReg', 'StartMeasurement')
# *** Get Decimal Values List ***
xyzDecimalValuesList = getXyzDecimalValuesList(deviceNickName)
outputListStr = ' ' + str(count).ljust(4) + str(datetime.now()).ljust(20) + ' = ' + \
str(xyzDecimalValuesList[0]).rjust(8) + ' ' + \
str(xyzDecimalValuesList[1]).rjust(8) + ' ' + \
str(xyzDecimalValuesList[2]).rjust(8)
outputListStrList[count] = outputListStr
sleep(pauseSeconds)
return outputListStrList
def printMeasurementResults(deviceNickname, measurementResultsList):
# *** Print Title ***
fprint.printTitleString ('ADXL345 Device Name', fprint.indentFormat640, deviceNickname)
print(' ')
print(' ----------------------------------------------------------------------')
fprint.printTitleString(' Time', fprint.indentFormat640, ' X value Y Value Z Value')
print(' ----------------------------------------------------------------------')
# *** Repeat Print Measurement Results ***
for measurementResults in measurementResultsList:
print(measurementResults)
print(' ----------------------------------------------------------------------')
return
def adxl345Test(deviceNickName):
fprint.printBeginExecFunction()
checkDeviceId('Jacky')
configDevice('Jacky')
measurementResultsList = getRepeatMeasurementResultsList(deviceNickName, 4, 0.01)
printMeasurementResults(deviceNickName, measurementResultsList)
fprint.printEndExecFunction()
return
# ******************************************************************************************************
# *** Main Test Functions ***
# ******************************************************************************************************
# *** SPI Tests ***
def spiBus00LoopbackOneByte():
testLoopBackOneByte('SpiBus00', 'TestByte0x5a')
return
def spiBus00LoopbackTwoBytes():
testLoopbackTwoBytes('SpiBus00', 'TestByte0x5a', 'TestByte0x5b')
return
def spiBus00LoopbackThreeBytes():
testLoopbackThreeBytes('SpiBus00', 'TestByte0x5a', 'TestByte0x5b', 'TestByte0x5c')
return
# *********************************************************
def spiLoopbackTest():
#testLoopBackOneByte('SpiBus01', 'TestByte0x5b')
#testLoopBackOneByte('SpiBus10', 'TestByte0x5c')
#testLoopBackOneByte('SpiBus11', 'TestByte0x5d')
#testLoopBackOneByte('SpiBus12', 'TestByte0x5e')
# *** Test loopbcak 1/2/3 Bytes for spiBus00 ***
#testLoopBackOneByte('SpiBus00', 'TestByte0x5a')
#testLoopbackTwoBytes('SpiBus00', 'TestByte0x5a', 'TestByte0x5b')
#testLoopbackThreeBytes('SpiBus00', 'TestByte0x5a', 'TestByte0x5b', 'TestByte0x5c')
# *** Test repeat send on byte for spiBus00 ***
#testRepeatSendOneByte('SpiBus00', 'TestByte0x5a', 'RepeatTimes100', 'PauseMilliSeconds10')
#testRepeatSendTwoBytes('SpiBus00', 'TestByte0x5a', 'TestByte0x5b', 'RepeatTimes100', 'PauseMilliSeconds10')
#testRepeatSendThreeBytes('SpiBus00', 'TestByte0x5a', 'TestByte0x5b', 'TestByte0x5c', 'RepeatTimes100', 'PauseMilliSeconds10')
return
# *** adxl345 Tests ***
# *** dummy function ***
def exit():
pass
return
# *** Menu Config ***
def readMainMenu():
fprint.printBeginExecFunction()
fmnu.execMenuList(mainMenu)
fprint.printEndExecFunction()
return
def readSpiMenu():
fprint.printBeginExecFunction()
fmnu.execMenuList(spiMenu)
fprint.printEndExecFunction()
return
def readAdxl345Menu():
fprint.printBeginExecFunction()
fmnu.execMenuList(adxl345Menu)
fprint.printEndExecFunction()
return
def readMoreMenu():
fprint.printBeginExecFunction()
print('Not yet ready!!!')
fprint.printEndExecFunction()
return
# *** Menu Config ***
mainMenu = ['########## Main Menu ##############################################################',
[['0', ['SPI Bus Tests', readSpiMenu]],
['1', ['ADXL345 Tests', readAdxl345Menu]],
['2', ['More Tests', readMoreMenu]],
['x', ['exitMenu()', exit]],
]
]
spiMenu = ['########## SPI Tests Menu ##########################################################',
[['0', ['spiBus00LoopxbackOneByte()', spiBus00LoopbackOneByte]],
['1', ['spiBus00LoopbackTwoBytes()', spiBus00LoopbackTwoBytes]],
['2', ['spiBus00LoopbackThreeBytes()', spiBus00LoopbackThreeBytes]],
['x', ['exitMenu()', exit]],
]
]
adxl345Menu = ['########## ADXL345 Tests Menu ##################################################',
[['0', ['adxl345Test()', adxl345Test]],
['1', ['adxl345Test()', adxl345Test]],
['2', ['adxl345Test()', adxl345Test]],
['x', ['exitMenu()', exit]],
]
]
# *** Main Tests ***
def main01():
#readMainMenu()
#spiBus00LoopbackOneByte()
adxl345Test('Jacky')
return
def main():
main01()
return
# ******************************************************************************************************
# *** Main ***
# ******************************************************************************************************
# main()
if __name__ == '__main__':
main()
# .END
# fprint171.py tlfong01 2019dec09hkt1241
import inspect
from datetime import datetime
# ********************************************************************************
# ********************************************************************************
# *** Print Config ***
indentFormat480 = [4, 80]
indentFormat608 = [6, 8]
indentFormat610 = [6, 10]
indentFormat615 = [6, 15]
indentFormat630 = [6, 30]
indentFormat640 = [6, 40]
# ** Print Functions ***
#def hexNumStrToFourCharStr(hexNumStr):
# hexNumStr = (hexNumStr[2:])
# if (len(hexNumStr) != 2):
# hexNumStr = '0' + hexNumStr
# hexNumStr = '0x' + hexNumStr
# return hexNumStr
def convertOneByteNumToFourCharStr(oneByteNum): # new <<<<<<<<<<
tempStr = ((hex(oneByteNum))[2:])
if (len(tempStr) != 2):
tempStr = '0' + tempStr
fourCharStr = '0x' + tempStr
return fourCharStr
def convertFourByteNumToTenCharStr(fourByteNum): # new <<<<<<<<<<
tempStr = ((hex(fourByteNum))[2:])
tempStr = '0' * (8 - len(tempStr)) + tempStr
tenCharStr = '0x' + tempStr
return tenCharStr
def convertOneByetNumToEightBitString(oneByteNum):
tempStr = ((bin(oneByteNum))[2:])
eightBitString = '0' * (8 - len(tempStr)) + tempStr
return eightBitString
#def convertTwoOneByteNumToEighteenBitStr(oneByteNum1, oneByteNum2):
# eighteenBitStr = '0b' + convertOneByetNumToEightBitString(oneByteNum1) + convertOneByetNumToEightBitString(oneByteNum2)
# return eighteenBitStr
def convert16BitTwoComplementToSignDecimal(twoComplementNum):
print(twoComplementNum)
return
def printTitle(title, indentFormat):
print((' ' * (indentFormat[0])), title.ljust(indentFormat[1]))
return
def printTitleNoNewLine(title, indentFormat):
print((' ' * (indentFormat[0])), title.ljust(indentFormat[1]), end = '')
return
def printTitleString(title, indentFormat, string):
printTitleNoNewLine(title, indentFormat)
print('=', string)
return
#def printTitleHexNum(title, indentFormat, hexNum):
# printTitleNoNewLine(title, indentFormat)
# print('=', hexNumStrToFourCharStr(hex(hexNum)))
# return
def printTitleOneByteNum(title, indentFormat, oneByteNum):
printTitleNoNewLine(title, indentFormat)
print('=', convertOneByteNumToFourCharStr(oneByteNum))
return
def printTitleOneByteNumToInteger(title, indentFormat, oneByteNum):
printTitleNoNewLine(title, indentFormat)
print('=', int(hex(oneByteNum), 16))
return
def printStarLine():
print('')
printTitle(('*' * 80), indentFormat480)
print('')
return
def printBeginExecFunction():
functionName = inspect.stack()[1][3]
title = 'Begin Execute Function ' + functionName + ' ' + str(datetime.now())[0:16]
printStarLine()
printTitle(title, indentFormat480)
print('')
printTitleString('Function Name', indentFormat640, functionName)
return
def printEndExecFunction():
title = 'End Execute Function ' + inspect.stack()[1][3] + ' ' + str(datetime.now())[0:16]
print('')
printTitle(title, indentFormat480)
printStarLine()
return
# ********************************************************************************
# ********************************************************************************
# *** Main Test Function ***
def testPrintFunctionExecutionName():
printBeginExecFunction()
print(' fourCharStr of 0x3 = ', convertOneByteNumToFourCharStr(0x3))
print(' tenCharStr of 0x0ffc3 = ', convertFourByteNumToTenCharStr(0x0ffc3))
printEndExecFunction()
return
# ********************************************************************************
# ********************************************************************************
# *** Main Tests ***
def mainTests():
#testPrintFunctionExecutionName()
#eightBitString = convertOneByetNumToEightBitString(0x06)
#print(eightBitString)
#eighteenBitString = convertTwoOneByteNumToEighteenBitStr(0x12, 0x45)
#print(eighteenBitString)
convert16BitTwoComplementToSignDecimal(0b0000000000000011)
convert16BitTwoComplementToSignDecimal(0b1111111111111100)
return
# ********************************************************************************
# ********************************************************************************
# *** Init/Main Functions ***
# *** Init Function ***
def init():
pass
return
#*** Main Function ***
def main():
init()
mainTests()
return
# ********************************************************************************
# ********************************************************************************
# *** Main ***
if __name__ == '__main__':
main()
# *** End of Program ***
# ********************************************************************************
# ********************************************************************************
# fi2c177.py tlfong01 2019dec10hkt1105
from time import sleep
from datetime import datetime
from signal import pause
import smbus
import fprint171 as fprint
import ftime73 as ftime
import os
import sys
# *** Contents ***
# 00. References
# 01. I2C Bus Config
# 02. Raspbian System Config Functions
# 03. I2C General Read/Write/Print Device/Register Functions
# 04. I2C Device Config
# 05. I2C Device Functions
# 06. I2C Device Test Functions
# 07. Reserved
# 08. Reserved
# 09. Reserved
# 10. I2C Init/Main Functions
# 11. Sample Outputs
# *** 0. Programming Notes and References ***
# 0.1 Set spi.mode = 3
# 0.2 Try self test (Datasheet Page 31)
# 0.3 Power sequencing (Datasheet Page 13)
# 0.3 Power supply decoupling note - (Datasheet Page 28)
# 0.4 ADXL355 Ouput Stuck At Zero - ADI Engineering Zone 2017dec05
# *** 1. I2c Bus Config ***
i2cBus1 = smbus.SMBus(1)
i2cBus3 = smbus.SMBus(3)
i2cBus4 = smbus.SMBus(4)
i2cBus6 = smbus.SMBus(6)
i2cBusDict = {'I2cBus1': i2cBus1,
'I2cBus3': i2cBus3,
'I2cBus4': i2cBus4,
'I2cBus6': i2cBus6,
}
# *** To Debug ***
# i2cBus5 = smbus.SMBus(5) # <<< not working *** !!!
#'I2cBus5': i2cBus5, # <<<<< Not working !!!
# *** System Functions ***
def pause(pauseTimeName):
sleep(i2cControlByteDict[pauseTimeName])
return
def convertTwoCompNumToDecNum(twoCompNum):
twoCompNumStr = bin(twoCompNum)
numBytes = 2
val = int(twoCompNumStr, numBytes)
b = val.to_bytes(numBytes, byteorder=sys.byteorder, signed = False)
return int.from_bytes(b, byteorder = sys.byteorder, signed = True)
i2cControlByteDict = {
'TenMilliSeconds' : 0.01,
'FourTimes' : 4,
'OneMillionTimes' : 1000000,
'TwentyMilliSeconds' : 0.02,
}
timeNowLong = str(datetime.now())
timeNowShort = str(datetime.now())[0:16]
# *** 2. System Config Functions ***
def getSystemInfo():
print('\n# *** System Info *****************************************************')
print('\n>>>>> ', 'Date', '<<<<<')
os.system('date')
print('\n>>>>> ', 'linux version', 'buster version, Rpi4B model, Rpi4B memory', '<<<<<')
os.system('cat /etc/issue.net')
os.system('uname -a')
os.system('grep Model /proc/cpuinfo')
os.system('grep MemTotal /proc/meminfo')
print('\n>>>>> ', 'i2c baudrate', '<<<<<')
os.system('grep dtparam=i2c /boot/config.txt')
print('\n>>>>> ', 'i2c dtoverlay', '<<<<<')
os.system('grep dtoverlay=i2c /boot/config.txt')
print('\n>>>>> ', 'ls /dev/i2c*', '<<<<<')
os.system('ls /dev/i2c*')
i2cdetectCommand = 'i2cdetect -y 1'
print('\n>>>>> ', i2cdetectCommand, '<<<<<')
os.system(i2cdetectCommand)
i2cdetectCommand = 'i2cdetect -y 3'
print('\n>>>>> ', i2cdetectCommand, '<<<<<')
os.system(i2cdetectCommand)
i2cdetectCommand = 'i2cdetect -y 4'
print('\n>>>>> ', i2cdetectCommand, '<<<<<')
os.system(i2cdetectCommand)
return
def getUartConfigInfo():
print('\n# *** UART BaudRate *****************************************************')
os.system('grep dtparam=i2c /boot/config.txt')
return
# *** 3. I2C Read Write Print Device/Register Functions ***
# *** Contents ***
# 3.1 quickWriteDevOneByte()
# 3.2 quickReadDevOneByte()
# 3.3 writeDevTwoBytes()
# 3.4 writeRegOneByte()
# 3.4 readDevOneByte
# 3.4 readDevReadByteAddrByteOneByte
# 3.4 readDevControlByteOneByte
# 3.4 readRegOneByte
# 3.4 printRegOneByte
# 3.4 writeDevThreeBytes
# *** Write/Read Device One Byte ***
# *** 3.1 ***
def quickWriteDevOneByte(i2cBus, devAddr, writeByte):
i2cBus.write_byte(devAddr, writeByte)
return
# *** 3.3 ***
def quickReadDevOneByte(i2cBus, devAddr):
readByte = i2cBus.read_byte(devAddr)
return readByte
# *** Write/Read/Print Device Two Bytes / Device Register One Byte ***
# *** 3.3 ***
def writeDevTwoBytes(i2cBus, devAddr, writeByte1, writeByte2):
i2cBus.write_byte_data(devAddr, writeByte1, writeByte2)
return
# *** 3.4 ***
def writeRegOneByte(i2cBus, devAddrDict, devAddrName, regAddrDict, regName, writeByte):
devAddr = devAddrDict[devAddrName]
regAddr = regAddrDict[regName]
writeDevTwoBytes(i2cBus, devAddr, regAddr, writeByte)
return
def readDevOneByte(i2cBus, devAddrAddr, readByteAddr):
readByte = i2cBus.read_byte_data(devAddr, readByteAddr)
return readByte
def readDevReadByteAddrByteOneByte(i2cBus, devAddrAddr, readByteAddr): # !!! Not Tested !!!
readByte = readDevOneByte(i2cBus, devAddrAddr, readByteAddr)
return readByte
def readDevControlByteOneByte(i2cBus, devAddr, controlByte):
readByte = i2cBus.read_byte_data(devAddr, controlByte)
return readByte
def readRegOneByte(i2cBus, devAddrDict, devName, regAddrDict, regName):
devAddr = devAddrDict[devName]
regAddr = regAddrDict[regName]
readByte = i2cBus.read_byte_data(devAddr, regAddr)
return readByte
def printRegOneByte(i2cBus, devAddrDict, devName, regAddrDict, regName):
readByte = readRegOneByte(i2cBusName, devAddrDict, devName, regAddrDict, regName)
print(printTitle, hex(readByte))
return
# *** Write Device Three Bytes ***
def writeDevThreeBytes(i2cBus, devAddr, WriteByte1, writeByte2, writByte3): # <<<<<<<<<< Not yet tested <<<<<<<<<<
i2cBus.write_block_data(devAddr, writeByte1, [writeByte2, writeByte3])
return
# *** 4. Device Write / Read / Print Register Functions ***
# *** Contents ***
# 4.1 readRegister()
# 4.2 writeVerifyRegister()
# 4.3 pingModule()
def readRegister(busName, devAddrDict, devAddrName, regAddrDict, regAddrName):
#fprint.printBeginExecFunction()
i2cBus = i2cBusDict[busName]
readByte = readRegOneByte(i2cBus, devAddrDict, devAddrName, regAddrDict, regAddrName)
#fprint.printEndExecFunction()
return readByte
def readVerifyRegister(moduleType, moduleNickName, busName, devAddrDict, devAddrName, regAddrDict, regAddrName, controlByteDict, verifyByteName):
#fprint.printBeginExecFunction()
i2cBus = i2cBusDict[busName]
verifyByte = controlByteDict[verifyByteName]
readByte = readRegOneByte(i2cBus, devAddrDict, devAddrName, regAddrDict, regAddrName)
if readByte == verifyByte:
verifyResultsString = 'Success'
else:
verifyResultsString = 'Failure'
devAddr = devAddrDict[devAddrName]
fprint.printTitleString('Date Time', fprint.indentFormat640, str(datetime.now())[0:16])
fprint.printTitleString('ModuleType', fprint.indentFormat640, moduleType)
fprint.printTitleString('ModuleNickName', fprint.indentFormat640, moduleNickName)
fprint.printTitleString('I2C Bus Name', fprint.indentFormat640, busName)
fprint.printTitleString('Device Addr Name', fprint.indentFormat640, devAddrName)
fprint.printTitleOneByteNum('Device Address', fprint.indentFormat640, devAddr)
fprint.printTitleString('Register Name', fprint.indentFormat640, regAddrName)
fprint.printTitleOneByteNum('VerifyByte', fprint.indentFormat640, verifyByte)
fprint.printTitleOneByteNum('Byte Read from Register', fprint.indentFormat640, readByte)
fprint.printTitleString('Verify Results', fprint.indentFormat640, verifyResultsString)
#fprint.printEndExecFunction()
return verifyResultsString
def writeVerifyRegister(moduleType, moduleNickName, busName, devAddrDict, devAddrName, regAddrDict, regAddrName, controlByteDict, writeByteName):
#fprint.printBeginExecFunction()
i2cBus = i2cBusDict[busName]
writeByte = controlByteDict[writeByteName]
writeRegOneByte(i2cBus, devAddrDict, devAddrName, regAddrDict, regAddrName, writeByte)
readByte = readRegOneByte(i2cBus, devAddrDict, devAddrName, regAddrDict, regAddrName)
if readByte == writeByte:
resultsString = 'Success'
else:
resultsString = 'Failure'
devAddr = devAddrDict[devAddrName]
fprint.printTitleString('Date Time', fprint.indentFormat640, str(datetime.now())[0:16])
fprint.printTitleString('ModuleType', fprint.indentFormat640, moduleType)
fprint.printTitleString('ModuleNickName', fprint.indentFormat640, moduleNickName)
fprint.printTitleString('I2C Bus Name', fprint.indentFormat640, busName)
fprint.printTitleString('Device Addr Name', fprint.indentFormat640, devAddrName)
fprint.printTitleOneByteNum('Device Address', fprint.indentFormat640, devAddr)
fprint.printTitleString('Register Name', fprint.indentFormat640, regAddrName)
fprint.printTitleOneByteNum('Byte Written to Register', fprint.indentFormat640, writeByte)
fprint.printTitleOneByteNum('Byte Read back from Register', fprint.indentFormat640, readByte)
fprint.printTitleString('Verify Results', fprint.indentFormat640, resultsString)
#fprint.printEndExecFunction()
return
def writeVerifyModuleRegister(moduleTypeName, moduleNickName, regAddrName, writeByteName):
#fprint.printBeginExecFunction()
moduleDict = moduleDictDict[moduleTypeName]
moduleType = moduleDict['ModuleType']
busName = moduleDict[moduleNickName]['I2cBusName']
controlByteDict = moduleDict['ControlByteDict']
devAddrDict = moduleDict['DevAddrDict']
devAddrName = moduleDict[moduleNickName]['DevAddrName']
regAddrDict = moduleDict['RegAddrDict']
regAddr = regAddrDict[regAddrName]
i2cBus = i2cBusDict[busName]
writeByte = controlByteDict[writeByteName]
writeRegOneByte(i2cBus, devAddrDict, devAddrName, regAddrDict, regAddrName, writeByte)
readByte = readRegOneByte(i2cBus, devAddrDict, devAddrName, regAddrDict, regAddrName)
if readByte == writeByte:
writeVerifyResultsString = 'Success'
else:
writeVerifyResultsString = 'Failure'
devAddr = devAddrDict[devAddrName]
fprint.printTitleString('Date Time', fprint.indentFormat640, str(datetime.now())[0:16])
fprint.printTitleString('ModuleType', fprint.indentFormat640, moduleType)
fprint.printTitleString('ModuleNickName', fprint.indentFormat640, moduleNickName)
fprint.printTitleString('I2C Bus Name', fprint.indentFormat640, busName)
fprint.printTitleString('Device Addr Name', fprint.indentFormat640, devAddrName)
fprint.printTitleOneByteNum('Device Address Byte', fprint.indentFormat640, devAddr)
fprint.printTitleString('Register Name', fprint.indentFormat640, regAddrName)
fprint.printTitleOneByteNum('Register Address Byte', fprint.indentFormat640, regAddr)
fprint.printTitleString('WriteByteName', fprint.indentFormat640, writeByteName)
fprint.printTitleOneByteNum('WriteByte (Written to Register)', fprint.indentFormat640, writeByte)
fprint.printTitleOneByteNum('ReadByte (Read from Register)', fprint.indentFormat640, readByte)
fprint.printTitleString('Write Verify Results', fprint.indentFormat640, writeVerifyResultsString)
#fprint.printEndExecFunction()
return writeVerifyResultsString
# Notes
# For Mode1 register, Test byte 0x88, 0x77 returns 0x58, 0x77. In other words, some bits are hardwired.
def pingModule(moduleTypeName, moduleNickName):
#fprint.printBeginExecFunction()
moduleDict = moduleDictDict[moduleTypeName]
moduleType = moduleDict['ModuleType']
busName = moduleDict[moduleNickName]['I2cBusName']
controlByteDict = moduleDict['ControlByteDict']
devAddrDict = moduleDict['DevAddrDict']
devAddrName = moduleDict[moduleNickName]['DevAddrName']
regAddrDict = moduleDict['RegAddrDict']
regAddrName = moduleDict['PingRegAddrName']
writeByteName = moduleDict['PingWriteByteName']
writeVerifyRegister(moduleType, moduleNickName, busName, devAddrDict, devAddrName, regAddrDict, regAddrName,
controlByteDict, writeByteName)
#fprint.printEndExecFunction()
return
def pingModuleList(moduleType, moduleNickNameList):
for moduleNickName in moduleNickNameList:
pingModule(moduleType, moduleNickName)
return
def readModuleRegister(moduleTypeName, moduleNickName, regAddrName):
#fprint.printBeginExecFunction()
moduleDict = moduleDictDict[moduleTypeName]
moduleType = moduleDict['ModuleType']
busName = moduleDict[moduleNickName]['I2cBusName']
controlByteDict = moduleDict['ControlByteDict']
devAddrDict = moduleDict['DevAddrDict']
devAddrName = moduleDict[moduleNickName]['DevAddrName']
regAddrDict = moduleDict['RegAddrDict']
readByte = readRegister(busName, devAddrDict, devAddrName, regAddrDict, regAddrName)
#fprint.printEndExecFunction()
return readByte
def readRegister(busName, devAddrDict, devAddrName, regAddrDict, regAddrName):
#fprint.printBeginExecFunction()
i2cBus = i2cBusDict[busName]
readByte = readRegOneByte(i2cBus, devAddrDict, devAddrName, regAddrDict, regAddrName)
#fprint.printEndExecFunction()
return readByte
def readVerifyModuleRegister(moduleTypeName, moduleNickName, registerName, verifyByteName):
#fprint.printBeginExecFunction()
moduleDict = moduleDictDict[moduleTypeName]
moduleType = moduleDict['ModuleType']
busName = moduleDict[moduleNickName]['I2cBusName']
controlByteDict = moduleDict['ControlByteDict']
devAddrDict = moduleDict['DevAddrDict']
devAddrName = moduleDict[moduleNickName]['DevAddrName']
regAddrDict = moduleDict['RegAddrDict']
regAddrName = moduleDict['PingRegAddrName']
readVerifyResult = readVerifyRegister(moduleType, moduleNickName, busName, devAddrDict, devAddrName,
regAddrDict, regAddrName, controlByteDict, verifyByteName)
#fprint.printEndExecFunction()
return
# *** 5. Device Config ***
# Contents
# 5.1 PCF8591 ADC/DAC Config
# 5.2 PCA9685 PWM Controller Config
# 5.3. MCP23017 IOX Config
# 5.4 ADXL345 Accelero Sensor Config
# *** 5.1 PCF8591 ADC/DAC Config ***
pcf8591DevAddrDict = {
'DevAddr0': 0x48,
'DevAddr1': 0x49,
'DevAddr2': 0x4a,
'DevAddr3': 0x4b,
'DevAddr4': 0x4c,
'DevAddr5': 0x4d,
'DevAddr6': 0x4e,
'DevAddr7': 0x4f,
}
pcf8591ControlByteDict = {
'ChannelNum0': 0x00,
'ChannelNum1': 0x01,
}
pcf8591ModuleDict = {
'ModuleType' : 'PCA9685',
#'ModuleHelp' : 'PwmControllerHelp',
#'DevAddrDict' : pca9685DevAddrDict,
#'RegAddrDict' : pca9685RegAddrDict,
#'ControlByteDict': pca9685ControlByteDict,
#'PingRegAddrName': 'Mode1',
'GreenTea': {'SignalName' : 'GreenTea',
'I2cBusName' : 'I2cBus4',
'DevAddrName' : 'DevAddr0',
'ChannelNumName' : 'ChannelNum0',
},
'Milk' : {'SignalName' : 'Yvalue',
'I2cBusName' : 'I2cBus4',
'DevAddrName' : 'DevAddr1',
'ChannelNumName': 'ChannelNum0',
},
'Water' : {'SignalName' : 'Yvalue',
'I2cBusName' : 'I2cBus4',
'DevAddrName' : 'DevAddr0',
'ChannelNumName': 'ChannelNum0',
},
'Oil' : {'SignalName' : 'Yvalue',
'I2cBusName' : 'I2cBus4',
'DevAddrName' : 'DevAddr1',
'ChannelNumName': 'ChannelNum0',
},
}
# *** 5.2 PCA9685 PWM Controller Config ***
pca9685DevAddrDict = {
'DevAddr0': 0x40,
'DevAddr1': 0x41,
'DevAddr2': 0x40,
'DevAddr3': 0x43,
'DevAddr4': 0x44,
'DevAddr5': 0x45,
'DevAddr6': 0x46,
'DevAddr7': 0x47,
}
pca9685RegAddrDict = { 'Mode1': 0x00,
'Mode2': 0x01,
}
pca9685ControlByteDict = {
'DataByte0x75' : 0x75,
'PingWriteByte' : 0x75,
}
pca9685ModuleDict = {
'ModuleType' : 'PCA9685',
'ModuleHelp' : 'PwmControllerHelp',
'DevAddrDict' : pca9685DevAddrDict,
'RegAddrDict' : pca9685RegAddrDict,
'ControlByteDict' : pca9685ControlByteDict,
'PingRegAddrName' : 'Mode1',
'PingWriteByteName' : 'PingWriteByte',
'Amy' : {'I2cBusName' : 'I2cBus1',
'DevAddrName' : 'DevAddr0',
},
'Betty' : {'I2cBusName' : 'I2cBus1',
'DevAddrName' : 'DevAddr1',
},
'Cindy' : {'I2cBusName' : 'I2cBus3',
'DevAddrName' : 'DevAddr0',
},
'Daisy' : {'I2cBusName' : 'I2cBus3',
'DevAddrName' : 'DevAddr2',
},
}
# *** 5.3 MCP23017 Iox Config ***
mcp23017DevAddrDict = {
'DevAddr0': 0x20,
'DevAddr1': 0x21,
'DevAddr2': 0x20,
'DevAddr3': 0x23,
'DevAddr4': 0x24,
'DevAddr5': 0x25,
'DevAddr6': 0x26,
'DevAddr7': 0x27,
}
mcp23017RegAddrDict = { 'IoDirRegAddrByteA': 0x00, }
mcp23017ControlByteDict = {
'DataByte0x55' : 0x55,
'DataByte0xaa' : 0xaa,
'PingWriteByte' : 0x55,
}
mcp23017ModuleDict = {
'ModuleType' : 'MCP23017',
'ModuleHelp' : 'Mcp23017IoxHelp',
'DevAddrDict' : mcp23017DevAddrDict,
'RegAddrDict' : mcp23017RegAddrDict,
'ControlByteDict' : mcp23017ControlByteDict,
'PingRegAddrName' : 'IoDirRegAddrByteA',
'PingWriteByteName' : 'PingWriteByte',
'Emily' : {'I2cBusName' : 'I2cBus1',
'DevAddrName' : 'DevAddr0',
},
'Fanny' : {'I2cBusName' : 'I2cBus1',
'DevAddrName' : 'DevAddr1',
},
'Gracie' : {'I2cBusName' : 'I2cBus1',
'DevAddrName' : 'DevAddr2',
},
'Heidi' : {'I2cBusName' : 'I2cBus1',
'DevAddrName' : 'DevAddr3',
},
'Ivy' : {'I2cBusName' : 'I2cBus1',
'DevAddrName' : 'DevAddr4',
},
}
# *** 5.4 ADXL345 Accelero Sensor Config ***
adxl345DevAddrDict = {
'DevAddr0': 0x1d,
}
adxl345RegAddrDict = {
'DevIdReg' : 0x00,
'DataFormatReg' : 0x31,
'PowerControlReg' : 0x2d,
'InterruptConfigReg' : 0x2e,
'DataX0' : 0x32,
'DataX1' : 0x33,
'DataY0' : 0x34,
'DataY1' : 0x35,
'DataZ0' : 0x36,
'DataZ1' : 0x37,
}
adxl345ControlByteDict = {
'DevIdByte' : 0xe5,
'Format16G13Bit' : 0x0B,
'StartMeasurement' : 0x08,
'InterruptDataReadyEnable' : 0x80,
'InterruptDataRedayDisable' : 0x00,
}
adxl345ModuleDict = {
'ModuleType' : 'ADXL345',
'ModuleHelp' : 'Adxl345AccelerometerHelp',
'DevAddrDict' : adxl345DevAddrDict,
'RegAddrDict' : adxl345RegAddrDict,
'ControlByteDict' : adxl345ControlByteDict,
'PingRegAddrName' : 'DevIdReg',
'PingWriteByteName' : 'DevIdByte',
'Jenny' : {'I2cBusName' : 'I2cBus1',
'DevAddrName' : 'DevAddr0',
},
}
# *** Module Dict Dict ***
moduleDictDict = {
'Pcf8591' : pcf8591ModuleDict,
'Pca9685' : pca9685ModuleDict,
'Mcp23017' : mcp23017ModuleDict,
'Adxl345' : adxl345ModuleDict,
}
# *** 6. Device Functions
# *** 6.1 PCF8591 ADC/DAC PhMeter ADC And Test Functions ***
# *** Read PCF8591 Single Ended Input Channel 0 ***
#def readAdcResults(i2cBus, devAddr, controlByte):
# adcResults = i2cBus.read_byte_data(devAddr, controlByte)
# adcResults = i2cBus.read_byte_data(devAddr, controlByte)
# return adcResults
# *** Device Functions ***
def pcf8591ConvertModule(moduleNickName):
# fprint.printBeginExecFunction()
moduleType = pcf8591ModuleDict['ModuleType']
i2cBusName = pcf8591ModuleDict[moduleNickName]['I2cBusName']
devAddrName = pcf8591ModuleDict[moduleNickName]['DevAddrName']
channelNumName = pcf8591ModuleDict[moduleNickName]['ChannelNumName']
i2cBus = i2cBusDict[i2cBusName]
devAddr = pcf8591DevAddrDict[devAddrName]
controlByte = pcf8591ControlByteDict[channelNumName]
# adcResults = readAdcResults(i2cBus, devAddr, controlByte)
adcResults = readDevControlByteOneByte(i2cBus, devAddr, controlByte)
adcResults = readDevControlByteOneByte(i2cBus, devAddr, controlByte)
print('\n# *** PCF8591 ADC Testing *****************************************************\n')
fprint.printTitleString('Module Type', fprint.indentFormat640, moduleType)
fprint.printTitleString('Module Nick Name', fprint.indentFormat640, moduleNickName)
fprint.printTitleString('I2C Bus Name', fprint.indentFormat640, i2cBusName)
fprint.printTitleOneByteNum('PCF8591 I2C Device Addr', fprint.indentFormat640, devAddr)
fprint.printTitleOneByteNum('Channel Number', fprint.indentFormat640, pcf8591ControlByteDict[channelNumName])
print(' ADC Results =', fprint.convertOneByteNumToFourCharStr(adcResults), ' (hex)')
print(' =', (str(adcResults)).ljust(4, ' '), ' (dec)')
print(' =', (str(int((float((adcResults)/255) * 100)))).ljust(4, ' '), ' (%)')
# fprint.printEndExecFunction()
return
def pcf8591ConvertModuleList(moduleNickNameList):
for moduleNickName in moduleNickNameList:
pcf8591ConvertModule(moduleNickName)
return
# *** PCF8591 ADC Test Functions ***
def testPcf8591ConvertDefaultModule():
pcf8591ConvertModule('GreenTea')
return
def testPcf8591ConvertModules():
pcf8591ConvertModule('GreenTea')
pcf8591ConvertModule('Milk')
pcf8591ConvertModule('Water')
pcf8591ConvertModule('Oil')
return
def testPcf8591ConvertModuleList():
pcf8591ConvertModuleList(['GreenTea', 'Milk', 'Water', 'Oil'])
return
# *** 6.2 PCA9865 PWM Controller Functions***
# *** Device Functions ***
# *** PCA9685 PWM Controller Functions ***
# *** Test Functions ***
# *** Test Repeat Write Register ***
# *** Test Repeat Write to PCA9685 PWM Controller ***
def testRepeatWriteRegister(): # <<<<<<<<<< Not tested!!!
getSystemConfig()
testRepeatWriteReadRegisterNoPrintResults('PCA9685', 'I2cBus1', 'Dev0', 'Mode1', '0x75', 'TenMilliSeconds', 'FourTimes')
testRepeatWriteReadRegisterNoPrintResults('PCA9685', 'I2cBus1', 'Dev0', 'Mode1', '0x75', 'TenMilliSeconds', 'OneMillionTimes')
return
# *** Test PCA9685 ***
def testPca9685PingDefaultModule():
pingModule('Pca9685', 'Amy')
return
def testPca9685PingModules():
pingModule('Pca9685', 'Amy')
pingModule('Pca9685', 'Betty')
pingModule('Pca9685', 'Cindy')
pingModule('Pca9685', 'Daisy')
return
def testPca9685PingModuleList():
pingModuleList('Pca9685', ['Amy', 'Betty', 'Cindy', 'Daisy'])
return
# *** Test MCP23017 ***
def testMcp23017PingDefaultModule():
pingModule('Mcp23017', 'Emily')
return
def testMcp23017PingModules():
pingModule('Mcp23017', 'Emily')
pingModule('Mcp23017', 'Fanny')
pingModule('Mcp23017', 'Gracie')
pingModule('Mcp23017', 'Heidi')
pingModule('Mcp23017', 'Ivy')
return
def testMcp23017PingModuleList():
pingModuleList('Mcp23017', ['Emily', 'Fanny', 'Gracie', 'Heidi', 'Ivy'])
return
# *** Test ADXL345 Accelerometer ***
def adxl345CheckDeviceId(moduleNickName):
#fprint.printBeginExecFunction()
# *** Ping Module ***
#pingModule('Adxl345', 'Jenny')
# *** Verify Mdoule Device Id ***
moduleTypeName = 'Adxl345'
print(' ----------------------------------------------------------------------')
readVerifyModuleRegister(moduleTypeName, moduleNickName, 'DevIdReg', 'DevIdByte')
#fprint.printEndExecFunction()
return
def testAdxl345PingDefaultModule():
fprint.printBeginExecFunction()
# *** Ping Module ***
#pingModule('Adxl345', 'Jenny')
# *** Verify Mdoule Device Id ***
readVerifyModuleRegister('Adxl345', 'Jenny', 'DevIdReg', 'DevIdByte')
fprint.printEndExecFunction()
return
# To delete 2019dec08hkt1456
#testWriteReadRegister('ADXL345', 'I2cBus1',
# adxl345DevAddrDict, 'DevAddr0',
# adxl345RegAddrDict, 'DeviceId',
# adxl345ControlByteDict, 'DataByte0x55')
#readByte = ReadRegister('I2cBus1', adxl345DevAddrDict, 'DevAddr0', adxl345RegAddrDict, 'DeviceId')
#print('Adxl345 DeviceId Reg =', hex(readByte))
def adxl345Init(moduleNickName):
moduleTypeName = 'Adxl345'
print(' ----------------------------------------------------------------------')
writeVerifyModuleRegister(moduleTypeName, moduleNickName, 'DataFormatReg', 'Format16G13Bit')
print(' ----------------------------------------------------------------------')
writeVerifyModuleRegister(moduleTypeName, moduleNickName, 'PowerControlReg', 'StartMeasurement')
print(' ----------------------------------------------------------------------')
writeVerifyModuleRegister(moduleTypeName, moduleNickName, 'InterruptConfigReg', 'InterruptDataReadyEnable')
print(' ----------------------------------------------------------------------')
pause('TwentyMilliSeconds')
return
def adxl345ReadOutput(moduleNickName):
moduleTypeName = 'Adxl345'
x0 = readModuleRegister(moduleTypeName, moduleNickName, 'DataX0')
x1 = readModuleRegister(moduleTypeName, moduleNickName, 'DataX0')
y0 = readModuleRegister(moduleTypeName, moduleNickName, 'DataY0')
y1 = readModuleRegister(moduleTypeName, moduleNickName, 'DataY1')
z0 = readModuleRegister(moduleTypeName, moduleNickName, 'DataZ0')
z1 = readModuleRegister(moduleTypeName, moduleNickName, 'DataZ1')
xTwoComp = (x1 << 8) | x0
yTwoComp = (y1 << 8) | y0
zTwoComp = (z1 << 8) | z0
xDecNum = convertTwoCompNumToDecNum(xTwoComp)
yDecNum = convertTwoCompNumToDecNum(yTwoComp)
zDecNum = convertTwoCompNumToDecNum(zTwoComp)
adxl345OutputList = [xDecNum, yDecNum, zDecNum]
#print(' x1, x0, y1, y0, z1, z0 =', hex(x1), hex(x0), ' ', hex(y1), hex(y0), ' ', hex(z1), hex(z0))
#print(x, ' ', y, ' ', z)
#print(hex(x), ' ', hex(y), ' ', hex(z))
#fprint.printTitleString('x, y, z', fprint.indentFormat640, (hex(x) + ' ' + hex(y) + ' ' + hex(z)))
#fprint.printTitleString('x, y, z', fprint.indentFormat640, (bin(x) + ' ' + bin(y) + ' ' + bin(z)))
#x18BitStr = fprint.convertTwoOneByteNumToEighteenBitStr(x0, x1)
#y18BitStr = fprint.convertTwoOneByteNumToEighteenBitStr(y0, y1)
#z18BitStr = fprint.convertTwoOneByteNumToEighteenBitStr(z0, z1)
#fprint.printTitleString('x', fprint.indentFormat608, x18BitStr)
#fprint.printTitleString('y', fprint.indentFormat608, y18BitStr)
#fprint.printTitleString('z', fprint.indentFormat608, z18BitStr)
return adxl345OutputList
def testAdxl345DefaultModule():
#os.system('i2cdetect -y 1')
adxl345CheckDeviceId('Jenny')
adxl345Init('Jenny')
print('')
print(' ----------------------------------------------------------------------')
fprint.printTitleString(' Time', fprint.indentFormat640, ' X value Y Value Z Value')
print(' ----------------------------------------------------------------------')
totalCount = 4
for count in range(totalCount):
adxl345OutputList = adxl345ReadOutput('Jenny')
outputListStr = str(adxl345OutputList[0]).rjust(8) + ' ' + str(adxl345OutputList[1]).rjust(8) + ' ' + str(adxl345OutputList[2]).rjust(8)
fprint.printTitleString(str(count).rjust(4) + ' ' + str(datetime.now()), fprint.indentFormat640, outputListStr)
sleep(0.5)
print(' ----------------------------------------------------------------------')
return
# *** Test All In One ***
def testAllInOne():
# *** Get System Info***
# getSystemInfo()
# *** Test Pcf8591 ADC/DAC ***
#testPcf8591ConvertDefaultModule()
#testPcf8591ConvertModules()
#testPcf8591ConvertModuleList()
# *** Test Pca9685 PWM Controller ***
#testPca9685PingDefaultModule()
#testPca9685PingModules()
#testPca9685PingModuleList()
# *** Test Mcp23017 GPIO Expander ***
#testMcp23017PingDefaultModule()
#testMcp23017PingModules()
#testMcp23017PingModuleList()
# *** Test Adxl345 Accelerometer ***
testAdxl345DefaultModule()
return
# *** 10. Init/Main Function ***
def init():
pass
return
def main():
init()
testAllInOne()
return
if __name__ == '__main__':
main()
# *** End of Program ********************************************************************
# *** 11. Sample Outputs ***
# *** End of Sample Output ***
Categories: Uncategorized
