通过串行

时间:2017-07-05 11:59:23

标签: python-3.x arduino pyserial

我一直在尝试通过串口向Python程序发送一个值到Arduino,但是我无法让Arduino存储并回显Python的值。我的代码似乎与我在网上的例子中找到的相匹配,但无论出于何种原因,它都无效。

我在Windows 10上使用带有Arduino Uno的Python 3.5。任何帮助将不胜感激。

Arduino代码:

void readFromPython() {
  if (Serial.available() > 0) {
    incomingIntegrationTime = Serial.parseInt();
    // Collect the incoming integer from PySerial
    integration_time = incomingIntegrationTime;
    Serial.print("X");
    Serial.print("The integration time is now ");
    // read the incoming integer from Python:
    // Set the integration time to what you just collected IF it is not a zero
    Serial.println(integration_time);
    Serial.print("\n");
    integration_time=min(incomingIntegrationTime,2147483648);
    // Ensure the integration time isn't outside the range of integers
    integration_time=max(incomingIntegrationTime, 1);
    // Ensure the integration time isn't outside the range of integers
  }
}

void loop() {
  readFromPython();
  // Check for incoming data from PySerial
  delay(1);
  // Pause the program for 1 millisecond
}

Python代码: (注意这与PyQt按钮一起使用,但是可以键入任何值而不是self.IntegrationTimeInputTextbox.text(),并且该值仍未被接收并由Arduino回显。)

def SetIntegrationTime(self):
    def main():
        #    global startMarker, endMarker
        #This sets the com port in PySerial to the port with the Genuino as the variable arduino_ports
        arduino_ports = [
            p.device
        for p in serial.tools.list_ports.comports()
        if 'Genuino' in p.description
        ]
        #Set the proper baud rate for your spectrometer
        baud =  115200
        #This prints out the port that was found with the Genuino on it
        ports = list(serial.tools.list_ports.comports())
        for p in ports:
            print ('Device is connected to: ', p)
        # --------------------------- Error Handling ---------------------------
        #Tell the user if no Genuino was found
        if not arduino_ports:
            raise IOError("No Arduino found")
        #Tell the user if multiple Genuinos were found
        if len(arduino_ports) > 1:
            warnings.warn('Multiple Arduinos found - using the first')
        # ---------------------------- Error Handling ---------------------------
    #=====================================
        spectrometer = serial.Serial(arduino_ports[0], baud)
        integrationTimeSend = self.IntegrationTimeInputTextbox.text()
        print("test value is", integrationTimeSend.encode())
        spectrometer.write(integrationTimeSend.encode())
        for i in range(10): #Repeat the following 10 times
            startMarker = "X"
            xDecoded = "qq"
            xEncoded = "qq"
            while xDecoded != startMarker:    #Wait for the start marker (X))
                xEncoded = spectrometer.read() #Read the spectrometer until 'startMarker' is found so the right amound of data is read every time
                xDecoded = xEncoded.decode("UTF-8");
                print(xDecoded);
            line = spectrometer.readline()
            lineDecoded = line.decode("UTF-8") 
            print(lineDecoded)
    #=====================================
        spectrometer.close()
    #===========================================

#WaitForArduinoData()
    main()

1 个答案:

答案 0 :(得分:1)

首先,这是一个问题:

incomingValue = Serial.read();   

因为read()会返回传入的串行数据reference第一个字节。在Arduino上int是一个带符号的16位整数,所以只用Serial.read()读取它的一个字节会给你带来意想不到的结果。

此外,不要在检查数据是否可用和实际读数之间进行写入:

 if (Serial.available() > 0) {
    Serial.print("X");                  // Print your startmarker
    Serial.print("The value is now ");
    incomingValue = Serial.read(); // Collect the incoming value from 

这很糟糕。而是在this example显示时立即阅读:

    if (Serial.available() > 0) {
            // read the incoming byte:
            incomingByte = Serial.read();

那是两个大问题。照顾好那些,让我们在纠正这些基本问题后再看看它。

第2部分

一旦纠正了这些,接下来要做的就是确定串行通信的哪一侧有故障。通常我喜欢做的是确定一方通过将其输出显示在终端仿真器中来正确发送。我喜欢TeraTerm。

将您的python代码设置为仅发送,并查看您发送的值是否在终端仿真器中正确显示。一旦这个工作,你对它有信心,你可以参加Arduino方面。