【问题标题】:python arduino usb communicationpython arduino usb 通讯
【发布时间】:2015-09-03 14:43:09
【问题描述】:

我正在尝试将数据从 Python 移动到 Arduino nano,但我在 Arduino 端的控制台上看不到任何内容,但是当 我尝试将数据从 Arduino 移动到 python,效果很好。 按照下面的代码:

arduino 代码

void setup() {   
     Serial.begin(9600);
 }
 void loop() {
     if(Serial.available() > 0) {
         char data = Serial.read();
         char str[2];
         str[0] = data;
         str[1] = '\0'
         Serial.print(str);     
     }
  }

python 代码

import serial, time
arduino = serial.Serial('COM3', 9600, timeout=.1)
time.sleep(1) # give the connection a second to settle
arduino.write("Hello from Python!")
while True:
    data = arduino.readline()
    if data:
        print data.rstrip('\n') # strip out the new lines

【问题讨论】:

  • 你有分隔符('\0') 并且需要关注它。 Serial.printlnSerial.print 没有相同的输出。
  • 可以给出更多解释,“focus it”是什么意思

标签: python-2.7 arduino communication


【解决方案1】:

Arduino 使用 print,Python 使用 readLINE。Readline 读取直到找到 '\n' arduino 永远不会发送 '\n'。'

\n 替换草图中的\0,它应该可以工作。

使用串行监视器进行测试并查看发生了什么总是有用的,如果这不起作用,请尝试使用串行监视器发送一些数据并让我们知道结果。

【讨论】:

    【解决方案2】:

    问题可能是你连接COM口后设置的时间太短了。

    试试这个

    time.sleep(5) # give the connection 5 seconds to establish
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-20
      • 1970-01-01
      • 2011-04-04
      • 1970-01-01
      • 2013-10-04
      • 1970-01-01
      相关资源
      最近更新 更多