微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Arduino Python 串行通信错误

如何解决Arduino Python 串行通信错误

这是一个复杂的错误,我已经有几个星期了,但我不知道如何修复它。我在第一个模拟引脚中插入了一个热敏电阻阵列,它们在 Python 脚本上返回温度,该脚本通过串行端口与 Arduino 通信。这是 Arduino 代码

float R1 = 2000;
float c1 = 8.7956830817e-4,c2 = 2.52439152444e-04,c3 = 1.94859260345973e-7;

void setup() {
  Serial.begin(9600);
  pinMode(13,OUTPUT);
  digitalWrite(13,HIGH);
  delay(1000);
  digitalWrite(13,LOW);
}

int getVoltage(int i) {
  return analogRead(i);
}

float getTemp(int i) {
  int V = getVoltage(i);
  float R2 = R1 * (1023.0 / (float)V - 1.0); \\minus 1 for 1 index based
  float logR2 = log(R2);
  float T = (1.0 / (c1 + c2*logR2 + c3*logR2*logR2*logR2));
  return T - 273.15;
}

String getTempString(int i) {
  float temp = getTemp(i);
  String result;
  if(temp > 99.99){
    return String(temp,2);
  } else {
    return String(temp,3);
  }
}

void loop() {
  if (Serial.available() > 0) {
    digitalWrite(13,HIGH);
    // read the incoming byte:
    String input = Serial.readStringUntil('\n');
    digitalWrite(13,LOW);
    //send the temperature
    char* response = new char[6];
    int channelNumber = String(input[0]).toInt() - 1;//-1 to make it index based 1
    getTempString(channelNumber).tochararray(response,6);
    //delay(20);
    Serial.write(response,6);
    Serial.write('\n');
  }
}

这里是 Python 代码

from serial import Serial
import time

ser = Serial('COM5',9600,timeout=1)

def readTempChannel(i):
    global ser
    
    ser.write(i+b'\n')
    raw = str.rstrip(ser.readline())
    try:
        return float(raw)
    except Exception:
        ser.close()
        ser = Serial('COM5',timeout=1)
        return 5.0[![enter image description here][1]][1]

if __name__ == "__main__":
    while 1:
        channel1 = readTempChannel('1')
        channel2 = readTempChannel('2')
        channel3 = readTempChannel('3')
        channel4 = readTempChannel('4')
        print('%.2f,%.2f,%.2f' % (channel1,channel2,channel3,channel4))

问题是我在前 10 秒得到了值,但之后我得到了空字符串或者我得到了不是来自 Arduino 的数字的随机字符。

我尝试关闭并重新打开串行端口,并且(有时)有效,但它会增加流的延迟,我需要为我的应用程序以高速进行通信而没有任何延迟。我在这文章添加一个屏幕截图,显示了 PuTTY 终端上的错误(Python 代码在 Beaglebone 上运行,它是 Python 2.7)。

所以如果你们中的任何人能帮助我解决这个错误,我将非常感激。

enter image description here

解决方法

在没有所有物理硬件的情况下,这是一个很难解决的问题,但我可以与您分享我在 arduino 中使用 pyserial 的经验:

在 python 方面,我没有打扰新行:

ser.write(b'{}'.format(command)) 
## writes the command as bytes to the arduino

我还使用以下行暂停 python 程序,直到它收到响应 - 这对于流控制非常重要

while(ser.inWaiting()==0):pass ## waits until there is data

在 arduino 方面,我使用以下内容读取串行并执行命令:

void loop() {
  switch(Serial.read()){
    case '0': ## when command (in python) = 0
              do_command_1()
              break;
    case '1': ## when command (in python) = 1
              do_command_2()
              break;
    default: break; # default - do nothing if I read garbage
  }
}

尝试将上述一些内容集成到代码中并回复我 - 就像我说没有硬件很难解决硬件问题,我这里的代码来自很久以前的项目

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。