从Mac向Arduino发送数据的Python代码出现问题

i2loujxw  于 2022-11-27  发布在  Python
关注(0)|答案(1)|浏览(139)

提前感谢您在这方面的任何帮助。
我正在编写一些代码,将数据从Mac发送到Arduino板,这样我就可以对闪存设备进行编程。我有一个Python程序,它协商到Arduino板的链接,然后将从文件读取的256字节数据块发送到Arduino。运行在Arduino上的代码使用SPI链接对256字节页面的存储设备进行编程。以下是Python代码:

import serial, time, sys

try:
    dataFile = open(sys.argv[1], "rb")
except IOError:
    sys.exit("file cannot be opened")  
arduino = serial.Serial('/dev/cu.usbmodem2101', 19200, timeout=1)
time.sleep(1) # give the connection a second to settle
arduino.write(("WAKEUP").encode('ascii'))
if( arduino.readline() != ("ACK").encode('ascii') ):
    sys.exit("no initial ACK from programmer")  
print("received initial ACK")
for block in range(1, 131073): # 256Mb is 131072 x 256B blocks
    blockData = dataFile.read(256)
    checksum = 256 - (sum(blockData) % 256) # checksum when added to summed data should result in 0
    arduino.write(blockData) # send the data
    arduino.write(checksum) # send the checksum
    if( arduino.readline() != ("ACK").encode('ascii') ): # wait for the block to be processed
        sys.exit("Failed to complete data transfer")
    print("Block = " + str(block) + " sent succesfully" )
arduino.close()
dataFile.close()

而不是发送数据的程序只是发送0x00一遍又一遍。如果我修改代码,从文件中读取一个字节的数据,一次发送一个字节的数据,它的工作正常。请任何人可以告诉我,我做错了什么上面显示的代码?

zdwk9cvp

zdwk9cvp1#

我在这方面做了一些工作,以修复一些与校验和相关的bug,下面的代码可以正常工作:

import serial, time, sys

try:
    dataFile = open(sys.argv[1], "rb")
except IOError:
    sys.exit("file cannot be opened")  
arduino = serial.Serial('/dev/cu.usbmodem2101', 115200, timeout=1)
time.sleep(1) # give the connection a second to settle
arduino.write(("WAKEUP").encode('ascii'))
if( arduino.readline() != ("ACK").encode('ascii') ):
    sys.exit("no initial ACK from programmer")  
print("received initial ACK")
for block in range(0, 16384): # 256Mb is 16384 x 2048B blocks
    blockData = dataFile.read(2048)
    checksum = (256 - (sum(blockData) % 256)) % 256 # checksum when added to summed data should result in 0
    arduino.write((blockData)) # send data
    if( checksum == 0) :
        arduino.write(bytearray([0]))
    else :
        arduino.write(checksum.to_bytes((checksum.bit_length() + 7) // 8, 'big')) # send the checksum
    if( arduino.readline() != ("ACK").encode('ascii') ): # wait for the block to be processed
        sys.exit("Failed to complete data transfer")
    print("Block = " + str(block) + " sent succesfully" )
arduino.close()
dataFile.close()

实在不明白它为什么会突然决定工作。

相关问题