簡體   English   中英

Python 代碼將數據從 Mac 發送到 Arduino 的問題

[英]Problem with Python code to send data from Mac to Arduino

提前感謝您對此的任何幫助。

我正在編寫一些代碼以將數據從 Mac 發送到 Arduino 板,以便我可以對 flash memory 設備進行編程。 我有一個 Python 程序,它協商到 arduino 板的鏈接,然后應該將從文件讀取的 256 字節數據塊發送到 arduino。在 Arduino 上運行的代碼使用 SPI 鏈接在 256 字節頁面中對 memory 設備進行編程。 這是 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。 如果我修改代碼以一次從文件中讀取一個字節的數據並一次發送一個字節的數據,它就可以正常工作。 請任何人告訴我上面顯示的代碼我做錯了什么?

我為此做了更多工作以修復一些與校驗和相關的錯誤,並且以下代碼有效:

    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()

真的不明白為什么它突然決定工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM