Python序列号到Arduin

2024-10-03 13:19:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我目前正试图用外部EEPROM向Arduino发送1024字节的数据。在

但是当运行这些代码时,传输常常在到达EOF之前停止,整个过程很奇怪。在

我的代码如下:

import binascii
import os
import serial
import time

ser = serial.Serial('/dev/ttyUSB0',9600)
recv = -1
counter = 0
totalcount = 0



with open('TestCard.txt', 'rb') as f:
    hexdata = binascii.hexlify(f.read())
    hexlist = map(''.join, zip(*[iter(hexdata)]*2))

f.close

while(1):


    #Wait for arduino to ask for address
    if(ser.readline()=="address\n"): 
        ser.write("0")
        print "written 0 \n" #Give arduino address I wanted to write
        break

for a in hexlist:

    ser.write("srq\n")
    #Check if arduino is good to revcieve data

    while(ser.readline() != "OK\n"):
        if(ser.readline() == "write\n"):
            print "write\n"
        ser.write("srq\n")
        print "srq\n"

    while(ser.readline() != "read\n"):
        if(ser.readline() == "read\n"):
            print "sok\n"
            ser.write("SOK\n")
            break

    print "sok\n"       
    ser.write("SOK\n")
    #Send data

    ser.write(a.encode())
    print "written " + a.encode()
    counter = counter + 1
    totalcount = totalcount + 1

    #else:
        #while(ser.readline()!="Next Block\n" and ser.readline()!="Done\n"):
            #continue
    if(counter == 16 ):
        print "\n\n16 bytes\n\n" 
        counter = 0


ser.write("EOF\n")
print "\nEOF\n"
ser.close()

还有我的阿杜伊诺素描:

^{pr2}$

整个数据流应该是这样的:

  1. Arduino继续发送address,直到它从serial收到一个地址。在
  2. Python将发送请求srq\n发送到serial。在
  3. Arduino继续读取串行输入并检查它是srq\n还是{}。在
  4. 如果是srq\n,Arduino发送OK\n。在
  5. Arduino发送read\n表示它已经准备好阅读了。在
  6. 如果收到read\n,Python将向Arduino发送“send OK”SOK\n
  7. Python开始发送数据
  8. 循环步骤1-6,直到发送完所有1024个字节。在
  9. Python发送EOF\n通知Arduino数据发送完成。在

我以为我的代码写得很正确,但不知怎么它就是不起作用。这一天我一直在努力解决。在

我的Python调试消息一直在打印write srq,数据传输常常在EOF之前停止(我知道这是因为Arduino板上的RX/TX指示灯将停止闪烁)

我一点也不熟悉串行,所以我不确定这是我的代码问题还是我对串行数据传输缺乏知识。
希望有人能帮我。在

如果不介意的话,可以从https://drive.google.com/open?id=1HLhxZfIcAf1iDZqIiWdlcYnRWB35MLqN下载1024字节的测试文件。在


Tags: 代码importreadreadlineifaddresscounterserial
1条回答
网友
1楼 · 发布于 2024-10-03 13:19:00

很抱歉我的直率,但你真的需要检查你的代码。你的代码中有不少错误。在

至于你的疑问, python打印write srq并等待的原因是由于以下代码部分

  while(checkSOK == false){

checkSOK是一个函数指针,其中as checkSOK()是一个函数。在

现在checkSOK的值永远不会为false,因此您的代码永远不会处理“SOK”\n,并且“SOK”中的4个字符成为16个十六进制文件字节的一部分,整个通信序列就会混乱。在

我真的不能理解您试图用这段代码实现什么,但是您应该知道,Arduino对警告非常宽容,因此在代码中发现问题可能相当困难。在

我建议使用Arduino首选项,并启用详细的错误和警告数据。在

我希望这有帮助,祝你好运。在

相关问题 更多 >