Python version of Arduino's Serial.available
<p>I'm trying to run an infinite loop in which the extension and movement of a linear actuator is controlled. The extension amount is controlled by user input with a value from 0 to 9, i.e. if I hit 9 and enter, the actuator will extend to maximum extension and if I hit 5 and enter, the actuator will go back to 50% extension.</p>

<p>I'm using a PINE A64+ with an MCP3008 connected to the Pi-2 bus and simply trying to replace a setup I had, with an Arduino + actuator, with a standalone embedded Linux setup.</p>

<p>I'm not sure how to go about having the program monitor raw_input consistently while running an infinite loop in the background. I was able to do this in my arduino code with the following:</p>

<pre><code>if (Serial.available() &gt; 0) {
  userInput = Serial.read()-48;
  Serial.println(userInput);
}
</code></pre>

<p>How would I go about doing something like this in Python? I've tried using PySerial's inWaiting command but that doesn't give me the same result. Essentially I want the program to do either one of the two possibilites:</p>

<ol>
<li>Use an if statement within the loop to only assign a new value to
the variable used if there is user input, or </li>
<li>To monitor for input constantly, and when there is an input, to break the loop, assign anew value for the variable being used by the loop, and re-enter the loop.</li>
</ol>

<p>It would look something like this:</p>

<pre><code># 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) &lt; getVal &lt; (positionArray[Terminal[0]] + 10):
    PWM0A.stop()
    PWM0B.stop()
elif getVal &gt; positionArray[Terminal[0]]:
    PWM0A.start(100)
    PWM0B.stop()
elif getVal &lt; positionArray[Terminal[0]]:
    PWM0A.stop()
    PWM0B.start(100)

# end loop
</code></pre>

<p>What's the best way of going about this? Thanks in advance :)</p>

<p>Answering my own question - I noticed I screwed up on the logic in my head a bit. I was trying to use the same internal serial port (the one I was using the execute the python script) to input information. Obviously this won't work. This is also why my inWaiting function was giving strange results.</p>

<p>Essentially, I opened a new COM port using serial.Serial (ttyS0), brought up a new terminal window to send data to ttyS0, then used the serial.inWaiting command to rerun the if statement each time a new value was entered. This time it was working correctly. Basically the same thing I did in my Arduino code. Doh :)</p>

python embedded-linux pyserial