And*_*lis 0 python byte serial-port type-conversion pyserial
我正在尝试执行一些串行输入和输出操作,其中之一是将8x8阵列发送到外部设备(Arduino)。该pySerial库需要,我发信息是字节。但是,在我的python代码中,8x8矩阵由types组成<class 'str'>
。这是我的发送功能:
import serial
import Matrix
width = 8
height = 8
portName = 'COM3'
def sendMatrix(matrix):
try:
port = serial.Serial(portName, 9600, timeout = 1000000)
port.setDTR(0)
print("Opened port: \"%s\"." % (portName))
receivedByte = port.read()
print(int(receivedByte))
if (receivedByte == '1'):
port.write('1')
bytesWritten = 0
for row in range(8):
for col in range(8):
value = matrix.getPoint(col, row)
bytesWritten += port.write(value)//ERROR HERE!
print(int(port.read()));
port.close()
print("Data (%d) sent to port: \"%s\"." % (bytesWritten, portName))
except:
print("Unable to open the port \"%s\"." % (portName))
def main():
matrix = Matrix.Matrix.readFromFile('framefile', 8, 8)
matrix.print()
print(type(matrix.getPoint(0, 0)))
print(matrix.getPoint(1, 1))
sendMatrix(matrix)
main()
Run Code Online (Sandbox Code Playgroud)
现在,我有一个类Matrix
,其中包含一个field map
,这是有问题的数组,我也将在此处包括该代码,但是我遇到的问题是数组中的每个元素都是type str
,但是我需要将其转换为字节。我可以忽略可能的数据丢失,因为在实践中,我仅使用0和1。
我的矩阵课:
class Matrix(object):
def __init__(self, width, height):
self.width = width
self.height = height
self.map = [[0 for x in range(width)] for y in range(height)]
def setPoint(self, x, y, value):
if ((x >= 0) and (x < self.width) and (y >= 0) and (y < self.height)):
self.map[y][x] = value
def getPoint(self, x, y):
if ((x >= 0) and (x < self.width) and (y >= 0) and (y < self.height)):
return self.map[y][x]
def print(self):
for row in range(self.height):
for col in range(self.width):
print(str(self.map[row][col])+" ", end="")
print()
def save(self, filename):
f = open(filename, 'w')
for row in range(self.height):
for col in range(self.width):
f.write(str(self.map[row][col]))
f.write('\n')
f.close()
def toByteArray(self):
matrixBytes = bytearray(self.width * self.height)
for row in range(self.height):
for col in range(self.width):
matrixBytes.append(int(self.map[row][col]))
return matrixBytes
def getMap(self):
return self.map
def readFromFile(filename, width, height):
f = open(filename, 'r')
lines = list(f)
matrix = Matrix(width, height)
f.close()
for row in range(len(lines)):
matrix.map[row] = lines[row].strip('\n')
return matrix
Run Code Online (Sandbox Code Playgroud)
在 Python 3.x 中,您可以使用如下所示的bytes
和str
。
>>> bytes('foo'.encode())
b'foo'
>>> a = bytes('foo'.encode())
>>> str(a.decode())
'foo'
Run Code Online (Sandbox Code Playgroud)
要将unicode字符串转换为Python中的字节字符串,请执行以下操作:
>>> 'foo'.encode('utf-8')
b'foo'
Run Code Online (Sandbox Code Playgroud)
要将字节字符串转换为Unicode字符串:
>>> b'foo'.decode('utf-8')
'foo'
Run Code Online (Sandbox Code Playgroud)