Python序列到Arduino

时间:2018-05-11 18:54:05

标签: python arduino pyserial

我目前正尝试将1024字节的数据发送到带有外部EEPROM的Arduino。

但是在运行这些代码时,传输通常会在达到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()

我的arduino草图:

#include <Wire.h>
#include <SoftwareSerial.h>

byte buff[16];
int addr=-1;
int count=0;
char readed[5];
char srq[4] = "srq\n";
char eof[4] = "EOF\n";
char sok[4] = "SOK\n";
byte recv;
bool ended = false;


void i2c_eeprom_write_byte( int deviceaddress, unsigned int eeaddress, byte data ) {
    int rdata = data;
    Wire.beginTransmission(deviceaddress);
    Wire.write((int)(eeaddress >> 8)); // MSB
    Wire.write((int)(eeaddress & 0xFF)); // LSB
    Wire.write(rdata);
    Wire.endTransmission();
}

// WARNING: address is a page address, 6-bit end will wrap around
// also, data can be maximum of about 30 bytes, because the Wire library has a buffer of 32 bytes
void i2c_eeprom_write_page( int deviceaddress, unsigned int eeaddresspage, byte* data, byte length ) {
    Wire.beginTransmission(deviceaddress);
    Wire.write((int)(eeaddresspage >> 8)); // MSB
    Wire.write((int)(eeaddresspage & 0xFF)); // LSB
    byte c;
    for ( c = 0; c < length; c++)
        Wire.write(data[c]);
    Wire.endTransmission();

}

byte i2c_eeprom_read_byte( int deviceaddress, unsigned int eeaddress ) {
    byte rdata = 0xFF;
    Wire.beginTransmission(deviceaddress);
    Wire.write((int)(eeaddress >> 8)); // MSB
    Wire.write((int)(eeaddress & 0xFF)); // LSB
    Wire.endTransmission();
    Wire.requestFrom(deviceaddress,1);
    if (Wire.available()) rdata = Wire.read();
    return rdata;
}

// maybe let's not read more than 30 or 32 bytes at a time!
void i2c_eeprom_read_buffer( int deviceaddress, unsigned int eeaddress, byte *buffer, int length ) {
    Wire.beginTransmission(deviceaddress);
    Wire.write((int)(eeaddress >> 8)); // MSB
    Wire.write((int)(eeaddress & 0xFF)); // LSB
    Wire.endTransmission();
    Wire.requestFrom(deviceaddress,length);
    int c = 0;
    for ( c = 0; c < length; c++ )
        if (Wire.available()) buffer[c] = Wire.read();
}

void LOL(char* arr)
{
  strcpy(arr, "LOL\n");
}  

bool checksrq(){
  bool same = false;
  for(int i=0 ; i<4; i++){
        readed[i] == srq[i] ? same = true : same = false;
    }

   return same;
}

bool checkEOF(){
  bool same = false;
  for(int i=0 ; i<4; i++){
        readed[i] == eof[i] ? same = true : same = false;
    }

   return same;
}

bool checkSOK(){
  bool same = false;
  for(int i=0 ; i<4; i++){
        readed[i] == sok[i] ? same = true : same = false;
    }

   return same;
}

void setup() {
  Wire.begin();
  Serial.begin(9600);
}

void loop() {
  // put your main code here, to run repeatedly:

      if(ended == true){
        delay(1000000);
      }

      while(addr==-1&& ended != true){
        Serial.print("address\n");
        addr = Serial.read();
        delay(500);
      }

      while(1){

          for(int i=0 ; i<4; i++){

            readed[i] = Serial.read();

          }

            if(checksrq()){
              delay(5);
              Serial.write("OK\n");
              LOL(readed);
              break;
            }else if(checkEOF()){
               ended = true;
            }
            LOL(readed);
            delay(1);
      }

      Serial.write("read\n");
      while(checkSOK == false){
        delay(1);
        Serial.write("read\n");
      }
      for(int i=0; i<16 ; i++){
        buff[i] = Serial.read();
        count++;
      }

      LOL(readed);

      if(count == 16 && ended != true){
          for(int i=0 ; i<16 ; i++){

              addr += i;
              //i2c_eeprom_read_byte(0x50,addr)!= buff[i] ? i2c_eeprom_write_byte(0x50,addr,buff[i]) :     delay(1);
              delay(5);
              Serial.write("write\n");

        }
          //i2c_eeprom_write_page(0x50, addr, buff, sizeof(buff));
          //delay(10);
          count = 0;
          Serial.write("Next Block\n");
      }
}

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

  1. Arduino继续发送address,直到收到来自序列号的地址。
  2. Python将发送请求srq\n发送到serial。
  3. Arduino不断阅读序列输入并检查它是srq\n还是EOF\n
  4. 如果是srq\n,Arduino会发送OK\n
  5. Arduino发送read\n表示已准备好阅读。
  6. Python将发送&#34;发送OK&#34;如果收到SOK\n
  7. ,则read\n到Arduino
  8. Python开始发送数据
  9. 循环步骤1-6,直到发送所有1024个字节。
  10. Python发送EOF\n告诉Arduino数据发送完成。
  11. 我认为我的代码编写正确,但不知何故它只是不起作用。我整天试图解决这个问题,但我真的陷入困境。

    我的Python调试消息只是保持打印write srq并且数据传输通常在EOF之前停止(我知道它因为Arduino板上的RX / TX LED将停止闪烁。)

    我根本不熟悉串口,所以我不确定这是我的代码问题还是我对串行数据传输缺乏了解。
    希望有人可以帮助我。

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

1 个答案:

答案 0 :(得分:0)

直言不讳道歉,但你真的需要检查你的代码。您的代码中存在相当多的错误。

至于你的查询, python打印写srq和等待的原因是因为代码的以下部分

df2

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

现在checkSOK的值永远不会为false,因此您的代码永远不会处理&#34; SOK \ n&#34;和#34; SOK \ n&#34;中的4个字符成为16个十六进制文件字节的一部分,整个通信序列变得混乱。

我无法真正了解您尝试使用此代码实现的目标,但您应该知道,Arduino对警告非常宽容,因此在代码中发现问题可能非常困难。

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

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