Uncategorized

fuart98

# Program = fuart98_2019oct1401.py tlfong01 2019oct14hkt2116
# Function = Test Rpi on board’s 5 UARTs and 4 USB to UART adapter/cable loop back and repeat send data
# Config = Rpi4B, raspbian 10 buster release 2019sep26, python 3.7.3 Thonny 3.2
# Ref = pyserial.readthedocs.io/en/latest/shortintro.html
# Setup = rpi-config > (1) Enable serial interface, (2) Disable serial console

# *** $ sudo nano /boot/config.txt to config 5 on board UARTs ***
# dtoverlay=uart5
# dtoverlay=uart4
# droverlay=uart3
# dtoverlay=uart2
# dtoverlay=uart1
# dtoverlay=uart0

# *** $ ls/ttyA*, ls /dev/ttyS* to confirm the there are 5 /dev/ttyAMAx serial devices ***
# /dev/ttyAMA0
# /dev/ttyAMA1
# /dev/ttyAMA2
# /dev/ttyAMA3
# /dev/ttyS0

# Contents
# 1. Tests brief description
# 2. Imports
# 3. Print functions
# 4. Menu functions
# 5. Serial functions
# 6. Test functions

# *** 1. Tests Brief Description ***

# Test 1 – Python string and byteArray datatype print demo
# Function – Print string and databyte variables
# Setup – None

# Test 2 – Repeat send bytes in databyte array, using scope to display TxD signal waveform
# Function – Repeat sending bytes, pause between bytes
# Setup – TxD (BCM GPIO #14, Rpi PCB 40 pin connector Pin #8)

# Test 3 – Loop back TxD output to Rxd.
# Function – Send bytes to TXD, wait (Note 1), receive bytes from RXD.
# Setup – Connet TxD, GPIO 14, Brd Pin 8, to RxD, GPIO 15, Brd Pin 10, to form a loopback.

# Test 4 – Send IR code ‘\xa1\xf1\x00\xff\x16’ (Mini Remote ontroller Digit 1 Button
# Function – Send IR code b’/bytes to TXD, wait (Note 1), receive bytes from RXD.
# Setup – Connet Rpi’s TxD pin to UART Interface IR emitter/receiver module’s RxD pin,
# Connect Another IR Emitter/Receiver’s TxD pin to Win10 RealTerm USB to UART TTL’s
# RxD pin. RealTerm configures to 9600, 8N1 and display to Hex.

# Results – (1) Rpi sends ‘\xa1\xf1\x00\xff\x16’,
# (2) UART Interface IR Emitter/Receiver red status LED blinks once.
# (3) RealTerm displays “00FF16″

# Test 5 – Repeat send bytes and loop back tests of TtyAMA 0, 1,2, 3, S0, 4 USB to Serial Ports

# Test 6 – Two Port port to port echo

# Note 1
# Bolutek BlueTooth BC04 needs at least 10mS to respond, will time out if not waiting.

# *** 2. Imports ***

from time import sleep
from datetime import datetime
import inspect
import serial
import serial.tools.list_ports

# *** 3. Print functions ***

format480 = [4, 80]
format630 = [6, 30]
format640 = [6, 40]

# ** Print Functions ***

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 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 printTitleOneByteNum(title, indentFormat, oneByteNum):
printTitleNoNewLine(title, indentFormat)
print(‘=’, convertOneByteNumToFourCharStr(oneByteNum))
return

def printStarLine():
print(”)
printTitle((‘*’ * 80), format480)
print(”)
return

def printBeginExecFunction(format1, format2):
printStarLine()
functionName = inspect.stack()[1][3]
printTitle(‘Begin Execute Function’, format1)
print(”)
printTitleString(‘Function name’, format2, functionName)
printTitleString(‘Time’, format2, str(datetime.now())[0:16])
return

def printEndExecFunction(format1):
print(”)
printTitle(‘End Execute Function’, format1)
printStarLine()
return

# *** 4. Menu Functions ***

def genMenu(menuList):
menuDict = {}
menuDict[‘Title’] = menuList[0]
menuDict[‘Dict’] = {}
for i in range(len(menuList[1])):
key = menuList[1][i][0]
menuDict[‘Dict’].update({menuList[1][i][0]: [menuList[1][i][1][0], menuList[1][i][1][1]]})
return menuDict

def printMenu(menuDict):
print(‘\n ***’, menuDict[‘Title’] + ‘ ***’)
print(”)
for key in (sorted(menuDict[‘Dict’].keys())):
print(key, ‘ =’, menuDict[‘Dict’][key][0])
print(‘x = exit’)
return

def execMenu(menuList):
menuDict = genMenu(menuList)
while (True):
printMenu(menuDict)
print(‘\nYour selection =’, ‘? ‘, end = ”)
keyStr = input()
if keyStr not in menuDict[‘Dict’].keys() and (not (keyStr == ‘x’ or keyStr == ‘m’ or keyStr == ‘w’)):
print(‘\nSelection = ERROR!!! Invalid selection. Try Again !!!’)
continue
if (keyStr == ‘x’):
print(‘\nFunction output =’, ‘Exit’)
break
print(”)
sleep(0.1)
menuDict[‘Dict’][keyStr][1]()
sleep(0.1)
return

def printHelloWorld():
printBeginExecFunction(format480, format640)
printTitleString(‘Function output’, format640, ‘Hello World!’)
printEndExecFunction(format480)
return

def printAbc123():
printBeginExecFunction(format480, format640)
printTitleString(‘Function output’, format640, ‘Abc123.’)
printEndExecFunction(format480)
return

exampleMenu = [‘Example Menu’,
[[‘0’, [‘printHelloWorld()’, printHelloWorld]],
[‘1’, [‘printAbc123()’, printAbc123]],
]
]

# *** 5. Serial Functions ***

def setupSerialPort(serialPortDeviceName, baudRate):
serialPort = serial.Serial(port = serialPortDeviceName,
baudrate = baudRate,
parity = serial.PARITY_NONE,
stopbits = serial.STOPBITS_ONE,
bytesize = serial.EIGHTBITS,
timeout= 1)
return serialPort

def setSerialPortBaudRate(serialPort, baudrate):
#print(‘ setting baudrate’)
print(‘ baudRate =’, baudrate)
serialPort.baudrate = baudrate
return

# *** Write bytes and repeat write bytes ***

def serialPortWriteBytes(serialPort, writeBytes):
serialPort.write(writeBytes)
return

def testSerailPortRepeatWriteBytes(serialPort, writeBytes, betweenBytePauseSeconds, repeatCount):
#print(‘ Begin repeatWriteOneByte(), …’)
for i in range(repeatCount):
serialPortWriteBytes(serialPort, writeBytes)
sleep(betweenBytePauseSeconds)
#print(‘ End repeatWriteOneByte().’)
return

# *** Read bytes ***

def serialPortReadBytes(serialPort, maxBytesLength):
readBytes = serialPort.read(maxBytesLength)
return readBytes

# *** Write-Wait-Read Bytes and Loopback ***

def serialPortWriteWaitReadBytes(serialPort, writeBytes, maxBytesLength, waitTime):
#print(‘\n*** Testing LoopBack ***’)
serialPort.flushInput()
serialPort.flushOutput()
serialPort.write(writeBytes)
sleep(waitTime)
readBytes = serialPortReadBytes(serialPort, maxBytesLength)
print(‘ bytes written = ‘, writeBytes)
print(‘ bytes read = ‘, readBytes)
return readBytes

def serialPortLoopBack(serialPort, writeBytes, maxBytesLength, waitTime):
#print(‘\n*** Begin serialPortLoopBack() [Remember to connect Tx to Rx!] ***’)
print(‘ Begin serialPortLoopBack(), …’)
serialPortWriteWaitReadBytes(serialPort, writeBytes, maxBytesLength, waitTime)
print(‘ End serialPortLoopBack(), …’)
return

# *** Serial Port Lists ***

def setupSerialPortList(serialPortDevNameList, baudrate):

serialPortList = [None for i in range(len(serialPortDevNameList))]

for i in range(len(serialPortList)):
#print(‘Name of Serial Port #’, i, ‘=’, serialPortDevNameList[i])
print(‘Now setting up serial port for ‘, serialPortDevNameList[i])
serialPortList[i] = setupSerialPort(serialPortDevNameList[i], baudrate)

#portList = serial.tools.list_ports.comports()
#print([port.name for port in portList])

return serialPortList

def setupSerialPort(serialPortDeviceName, baudrate):
serialPort = serial.Serial(port = serialPortDeviceName,
baudrate = baudrate,
parity = serial.PARITY_NONE,
stopbits = serial.STOPBITS_ONE,
bytesize = serial.EIGHTBITS,
timeout= 1)
return serialPort
def closeSerialPortList(serialPortList): # *** buggy ***
for serialPort in serialPortList:
pass
#serialPort.close()
#close(serialPort)
return

# *** 6. Test Functions ***

# *** Testing print python string and byteArray (Just printing, not using serial) ***

def testPrintString01():
print(‘\n*** Begin Testing Print String ***’)
testString1 = ‘abc’
print(‘ testString1 =’, testString1)
testCharArray2 = [‘x’, ‘y’, ‘z’]
print(‘ testStringArray2 =’, testCharArray2)
testString3 = testCharArray2[0] + testCharArray2[1] + testCharArray2[2]
print(‘ testString3 =’, testString3)
print(‘*** End Testing Print String ***’)
return

# *** Testing bytearray ***

def testPrintByteArray01():
print(‘\n*** Begin Testing Print ByteArray ***’)
testByteArray4 = b’AT\r\n’
print(‘ testByteArray4 =’, testByteArray4)
testString5 = testByteArray4.decode(‘utf-8’)
print(‘ testString5 =’, testString5)
print(‘*** End Testing Print ByteArray ***’)
return

def testSerialRepeatSendBytes01():
print(‘\n*** Begin Test Repeat Write Bytes ***’)

serialPort = serialPort0
baudrate = 9600
pauseSeconds = 0.01
repeatCount = 100

writeBytes = b’\x00\xff\x55\xff\x00′

#print(‘ Begin repeatWriteOneByte(), …’)
print(‘ Write byte =’, writeBytes)
print(‘ Pause second between writes =’, pauseSeconds)
print(‘ Repeat count =’, repeatCount)

setSerialPortBaudRate(serialPort, baudrate)
testSerailPortRepeatWriteBytes(serialPort, writeBytes, pauseSeconds, repeatCount)
print(‘*** End Test Repeat Write Bytes. ***’)
return

def testSerialLoopbackBytes01(): # ‘/dev/serial0’, (Using Rpi UART GPIO pins TsD, RxD)
print(‘\n*** Begin Test Serial Port Loopback = /dev/serial0 ***’)
serialPort = serialPort0
writeBytes = b’abcxyz’
maxBytesLength = 32
waitTime = 0.01
serialPortLoopBack(serialPort, writeBytes, maxBytesLength, waitTime)
print(‘*** End Test Serial Port Loopback ***’)
return

def testSerialLoopbackBytes02(): # ‘/dev/ttyUSB0’, Using USB to UART/TTL adapter/cable
print(‘\n*** Begin Test Serial Port Loopback = /dev/ttyUSB0 ***’)
serialPort = serialPort1
writeBytes = b’abcxyz’
maxBytesLength = 32
waitTime = 0.01
serialPortLoopBack(serialPort, writeBytes, maxBytesLength, waitTime)
print(‘*** End Test Serial Port Loopback ***’)
return

def testSerialLoopbackBytes03(): # ‘/dev/ttyUSB1’, Using USB to UART/TTL adapter/cable
print(‘\n*** Begin Test Serial Port Loopback /dev/ttyUSB1 ***’)
serialPort = serialPort2
writeBytes = b’abcxyz’
maxBytesLength = 32
waitTime = 0.01
serialPortLoopBack(serialPort, writeBytes, maxBytesLength, waitTime)
print(‘*** End Test Serial Port Loopback ***’)
return

# *** LIRC Test Functions ***

def testSendIrCode01():
print(‘\n*** Begin Test Send IR Code ***’)
serialPort = serialPort0
serialPort.flushInput()
serialPort.flushOutput()
writeBytes = b’\xa1\xf1\x00\xff\x16′ # Mini Remote Controller #1 Digit 1 Button code
serialPort.write(writeBytes)
print(‘ bytes written = ‘, writeBytes)
print(‘*** End Test Send IR Code ***’)
return

def serialTwoPortEcho(serialPortX, serialPortY):
print(‘\n*** Begin Test Two Port Echo ***’)

maxBytesLength = 32
waitTime = 0.01

serialPortX.flushInput()
serialPortX.flushOutput()

serialPortY.flushInput()
serialPortY.flushOutput()

writeBytes = b’123abc’
serialPortX.write(writeBytes)
print(‘ SerialPortX bytes written = ‘, writeBytes)

readBytes = serialPortY.read(maxBytesLength)
print(‘ SerialPortY bytes read = ‘, readBytes)

writeBytes = b’456xyz’
serialPortY.write(writeBytes)
print(‘ SerialPortY bytes written = ‘, writeBytes)

readBytes = serialPortX.read(maxBytesLength)
print(‘ SerialPortX bytes read = ‘, readBytes)

print(‘*** End Test Two Port Echo ***’)
return

# *** 5 On board UART tests ***

# *** Main Tests ***

# *** Individual Tests ***

def individualTests01(): # Individual Tests
#print(‘\n*** firc71_2019sep2201.py tlfong01 2019sep22hkt1206 ***\n’)

# *** Preliminary UART Test ***
#testPrintString01()
# testPrintByteArray01()
# testSerialRepeatSendBytes01()
# testSerialLoopbackBytes01()

# *** IR Signal Send/Receiver Test ***
# testSendIrCode01()

# *** Loop back test of three serial ports ***

# testSerialLoopbackBytes01() # loopback ‘/dev/serial0’
# testSerialLoopbackBytes02() # loopback ‘/dev/ttyUSB0’
# testSerialLoopbackBytes03() # loopback ‘/dev/ttyUSB1’

# *** Serial Port 2 Echos Serial Port 1 ***

#serialPort0Port1EchoTest01()
#serialPort1Port2EchoTest01()

# serialTwoPortEcho(serialPort0, serialPort1)
#serialTwoPortEcho(serialPort1, serialPort2)

return

# *** Menu Tests ***

# *** Menu Functons ***

def execMainMenu():
execMenu(mainMenu)
return

def execExampleMenu():
execMenu(exampleMenu)
return

def execStringByteArrayMenu():
execMenu(stringByteArrayMenu)
return

def execSerialMenu():
execMenu(serialMenu)
return

def execSerialLoopbackMenu():
execMenu(serialLoopbackMenu)
return

# *** Menmus ***

mainMenu = [‘Main Menu’,
[[‘0’, [‘Example menu’, execExampleMenu]],
[‘1’, [‘String byteArray menu’, execStringByteArrayMenu]],
[‘2’, [‘Serial menu’, execSerialMenu]],
]]

stringByteArrayMenu = [‘Print String ByteArray Menu’,
[[‘0’, [‘Print string’, testPrintString01]],
[‘1’, [‘Print byteArray’, testPrintByteArray01]],
]]

serialMenu = [‘Serial Menu’,
[[‘0’, [‘Serial loopback’, execSerialLoopbackMenu]],
#[‘1’, [‘Repeat write bytes’, execRepeatWriteBytesMenu]],
]]

serialLoopbackMenu = [‘Serial Loopback Menu’,
[[‘0’, [‘Loopback serialPort 1 (/dev/serial0)’, testSerialLoopbackBytes01]],
[‘1’, [‘Loopback serialPort 2 (/dev/ttyUSB0)’, testSerialLoopbackBytes02]],
[‘2’, [‘Loopback serialPort 3 (/dev/ttyUSB1)’, testSerialLoopbackBytes03]],
]]

# *** Main Tests ***

#individualTest01()
#testExampleMenu()
#menuTestPrintString01()
#execMainMenu()

#serialPortDevNameList = [‘/dev/serial0’, ‘/dev/ttyUSB0’, ‘/dev/ttyUSB1’]

serialPortDevNameList = [‘/dev/ttyAMA0’]
serialPortList = setupSerialPortList(serialPortDevNameList, baudrate = 9600)

#serialPort = setupSerialPort(‘/dev/ttyS0’, baudrate = 9600)
#serialPort = setupSerialPort(‘/dev/ttyAMA0′, baudrate = 9600)

#closeSerialPortList(serialPortList)

# *** End of Program ***

# ****************************************************************************
# ****************************************************************************
# ****************************************************************************
# *** Sample output tlfong01 2019oct03 ***

”’
Python 3.7.3 (/usr/bin/python3)
>>> %Run fuart78.py

*** Begin Test Two Port Echo ***
SerialPortX bytes written = b’123abc’
SerialPortY bytes read = b’123abc’
SerialPortY bytes written = b’456xyz’
SerialPortX bytes read = b’456xyz’
*** End Test Two Port Echo ***
>>>
”’

# *** Sample output tlfong01 2019apr0801 ***

”’
>>> %Run fuart71.py

*** Begin Testing Print String ***
testString1 = abc
testStringArray2 = [‘x’, ‘y’, ‘z’]
testString3 = xyz
*** End Testing Print String ***

*** Begin Testing Print ByteArray ***
testByteArray4 = b’AT\r\n’
testString5 = AT

*** End Testing Print ByteArray ***

*** Begin Test Repeat Write Bytes ***
Write byte = b’\x00\xffU\xff\x00′
Pause second between writes = 0.01
Repeat count = 100
baudRate = 9600
*** End Test Repeat Write Bytes. ***

*** Begin Test Serial Port Loopback ***
Begin serialPortLoopBack(), …
bytes written = b’abcxyz’
bytes read = b’abcxyz’
End serialPortLoopBack(), …
*** End Test Serial Port Loopback ***

”’

”’
>>> %Run fuart71.py

*** Begin Test Send IR Code ***
bytes written = b’\xa1\xf1\x00\xff\x16′
*** End Test Send IR Code ***

”’

# ****************************************************************************
# ****************************************************************************
# ****************************************************************************

# *** End of Sample Outputs ***

# *** End ***

Categories: Uncategorized

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s