Python版的Arduino的Serial.available

时间:2016-09-09 17:36:55

标签: python embedded-linux pyserial

我正在尝试运行无限循环,其中控制线性执行器的伸展和移动。延伸量由用户输入控制,值为0到9,即如果我按9并进入,则执行器将延伸到最大延伸,如果我按5并进入,则执行器将返回到50%延伸。 / p>

我正在使用PINE A64 +,MCP3008连接到Pi-2总线,只是尝试使用独立的嵌入式Linux设置替换我使用Arduino +执行器的设置。

我不确定如何让程序在后台运行无限循环时始终如一地监视raw_input。我能够在我的arduino代码中执行以下操作:

if (Serial.available() > 0) {
  userInput = Serial.read()-48;
  Serial.println(userInput);
}

我如何在Python中做这样的事情?我已经尝试过使用PySerial的inWaiting命令,但这并没有给我相同的结果。基本上我希望程序能够做到两个可能中的任何一个:

  1. 在循环中使用if语句仅为其分配新值 如果有用户输入,则使用的变量,或
  2. 要持续监视输入,当有输入时,要打破循环,为循环使用的变量分配一个新值,然后重新进入循环。
  3. 它看起来像这样:

    # begin loop w/ while True statement
    
    # using if statement to enter only if there is user input, otherwise pass over
    if Whatever:
        Terminal[0] = user input
    
    getVal = analogRead(0, PI2CLK, PI2MOSI, PI2MISO, PI2CS) 
    
    if (positionArray[Terminal[0]] - 10) < getVal < (positionArray[Terminal[0]] + 10):
        PWM0A.stop()
        PWM0B.stop()
    elif getVal > positionArray[Terminal[0]]:
        PWM0A.start(100)
        PWM0B.stop()
    elif getVal < positionArray[Terminal[0]]:
        PWM0A.stop()
        PWM0B.start(100)
    
    # end loop
    

    最好的解决方法是什么?在此先感谢:)

2 个答案:

答案 0 :(得分:0)

来自the documentation

 in_waiting
    Getter: Get the number of bytes in the input buffer
    Type:   int

    Return the number of bytes in the receive buffer.

答案 1 :(得分:0)

回答我自己的问题 - 我注意到我的脑子里的逻辑搞砸了。我试图使用相同的内部串行端口(我使用执行python脚本的那个)来输入信息。显然这不起作用。这也是我的inWaiting功能给出奇怪结果的原因。

基本上,我使用serial.Serial(ttyS0)打开一个新的COM端口,启动了一个新的终端窗口将数据发送到ttyS0,然后每次输入新值时使用serial.inWaiting命令重新运行if语句。这次它工作正常。基本上我在Arduino代码中做了同样的事情。 Doh:)