我想制作一个Python代码来读取串行数据,将其转换为二进制表示形式,然后将其写入.txt文件。所有传入的数据均为uint8类型(0到255之间的值),它们之间有一个空格。我在SO上找到了一个'int2bin'函数,我认为这样可以工作。
“主”中的代码:
if __name__ == '__main__':
#setup
ser = serial.Serial('COM18', 19200)
temp = ''
intVal = []
path = 'C:\Users\mabr\Desktop\TEST'
name = 'fileFromEEPROM'
myFile = open(join(path, name),"w")
while ser.in_waiting<1:
sleep(1)
while ser.in_waiting>0:
if ser.read(1) != ' ':
intVal[0:] = ser.read()
newData = True
if ser.read(1) == ' ':
ser.read(1)
if newData == True:
binVal = modules.int2bin(intVal, 8) #This is where the error is
myFile.write(binVal)
#temp += binVal
newData = False
intVal[:] = [] #emptying
myFile.close()
“模块”中的代码:
def int2bin(integer, digits):
if integer >= 0:
return bin(integer)[2:].zfill(digits) #This is where the error is
else:
return bin(2**digits + integer)[2:]
我得到错误代码: “文件“ C:\ Users \ mabr \ Documents \ int8ToAscii \ src \ modules.py”,第10行,在int2bin中 返回bin(整数)[2:]。zfill(数字) TypeError:“列表”对象无法解释为索引”
我认为函数int2bin的目标是很容易解释的,但重点是它应该将intVal中存储的整数转换为二进制并返回结果。
我认为我可能在存储串行数据的方式上犯了一个错误,这可能是错的,但是我不确定如何将最多3位数字存储为一个整数(作为一个整数例如,可能会收到“ 255”,但我不知道它会存储在intVal的单独条目中,例如“ intVal [] = {'2','5','5'})。
如果我遗漏了一些东西,请发表评论。我对SO还是很陌生,可能没有提到重要的事情。谢谢。