强大的Arduino-Python串行通信



我正在研究python通过USB将电机命令发送到Arduino Mega的项目。我一直在尝试如何使代码健壮的几种变体,以便 python 程序等到 arduino 准备好接收。这是这个问题的超级基本版本。

错误在于arduino

println成功发送回该值,以便在arduino IDE的串行监视器中读取。但是 python 没有成功读取它以将值打印到命令行。

我的 python 读取代码有什么问题?

阿杜伊诺

//++++++++++++++++++++Initializations+++++++++++++++++++++
int command = 0;
int control = 0;
boolean newInput = 0;
int myCount = 0;
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
void setup() {
  Serial.begin(9600);                    // set the baud rate
  Serial.println(1);                     // initial "ready" signal
}
void loop() {
   // read sent command and return it
    if(Serial.available() > 0){         // only send data back if data has been sent
      command = Serial.read();
      delay(10);
      Serial.println(1);                // send "ready" signal
      delay (50);                       //alternatively Serial.flush();
      myCount++;
    } 
}

这是我的程序的精简版本,突出了这个问题。

import serial
ser = serial.Serial('/dev/ttyACM0', 9600, timeout = 1)
import time
controlBit = True
n = 0
charsWait = 0   #chars waiting from arduino
print "Starting up"
connected = False
while True:
    n = n+1
    print n
    print "Writing"
    ser.write(str(2))
    time.sleep(1)
    while True:
        try:
            print "reading"
            charsWait = ser.readline()
            time.sleep(1)
            print "   = value recieved", charsWait 
            break
        except:
            pass
    print "restart"
    ser.flush() #flush the buffer
<pre>Arduino code:
    //++++++++++++++++++++Initializations+++++++++++++++++++++
    int command = 0;
    int control = 0;
    boolean newInput = 0;
    int myCount = 0;
    
    //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    
    void setup() {
      Serial.begin(9600);                    # set the baud rate
      Serial.println("1");                    # initial "ready" signal
    }
    
    void loop() 
    {
       # read sent command and return it
        if(Serial.available() > 0)
        {
          command = Serial.read();
          Serial.println(command);                
        } 
    }
    
    
#Python Code for is waiting for Arduino listening state.
    import serial
    ser = serial.Serial('/dev/ttyACM0', 9600, timeout = 1)
    
    import time
    
    controlBit = True
    n = 0
    charsWait = 0   #chars waiting from Arduino
    
    print "Starting up"
    connected = False
    
    while True:
        charsWait = ser.read()   #ser.read data in ASCII
        print "   = value recieved", charsWait 
        if charsWait == 49:      #ASCII of 1=49**strong text**
             while True:
                 ser.write("As per you")       

#means 当Arduino安装程序运行时(Arduino初始化时间),Arduino发送"1"python正在等待接收"1"后1他们可以工作。

最新更新