Search code examples
pythoncpu-usagehardwarepyserialserial-communication

Does cpu usage affect reading of serial data?


I'm not sure if this is an obvious question, but I am somewhat new to serial communication (at least never thought about it in this depth) and extremely new to Python. I have a Raspberry Pi and a linear actuator. The linear actuator has an API that provides functions that use PySerial to read and write to the hardware, and these are what I use to try and talk to the actuator.

I have implemented a more involved code that receives request data via DDS, but ultimately the purpose of the code is to write the position value extracted from that request data to the linear actuator, and in return receive the linear actuator's position value. It can write to the hardware OK, and the linear actuator extends/retracts as needed, but reading position feedback from the hardware results to a timeout & if I increase timeout value or change serial.read() to serial.read(1) (by changing the code in the API directly), it reads b'' instead. I noticed that my code, when being run, uses 100.7% CPU. By the time I read, it goes up to 101%.

There is another more basic code that I have with only a few lines that simply reads and writes to the linear actuator without the DDS stuff. Instead the position value that gets passed down to the actuator is hard-coded. This one uses the same read/write functions from the API as is without changes like I had to do for the other code. When testing with this very basic code, it only shows 5% CPU usage and reads position feedback just fine.

I couldn't understand why it would work for the basic code and not for other, especially since the sequence of actions are the same when writing/reading, and the same exact functions and parameters are used. I was beginning to wonder if somehow the high CPU usage for the more involved code affects reading of serial data.

Do any of you know whether high CPU usage would affect PySerial's ability to read data or not? Is there a correlation between the two?


Solution

  • If you are hitting the ceiling of your CPU usage, it is possible that the PySerial process that is reading the data is not able to complete each cycle before the next sampling window (e.g. your code wants a sample per second, but the cycle takes two seconds to complete). Adding too many processes or CPU-heavy processes will eventually lead to the CPU being a bottleneck.