Wednesday, October 23, 2024

PySerial talking to an Arduino can be slow. Putting an http server in between is one solution. Also which language? Yeah whatever.

This week I discovered how unacceptably slow Python can be when talking to an Arduino via PySerial.  I have an arduino controller driving some stepper motors, and it won't answer "OK" until the steppers have finished executing the requested movement.  Python introduced an extra 5-6 seconds per move instruction, when compared to issuing the same move commands from a TeraTerm script doing the same thing.  So there wasn't anything wrong with the Arduino controller - all the blame sat on the Python side.  I tried several suggestions I found online and none of them got me any closer.  It's wierd because if I modded the Arduino controller to just be an echo of any incoming characters, then Python was instanteous in handling the responses and going to the next command.

To work around this, I set up an http server (specifically with Go - and I only chose that because I was hitting my head when I tried to include Crow in C++, and I really don't care which language the server is in, all I cared about was verifying that Python would work better and as fast as I possibly could verify that, so, sorry C++, maybe next time).

This is an interesting side-note.  Languages don't mean what they used to, especially when one is brand new to me and the other I haven't used in quite a while, or never for some application.  For a simple little http server talking to a serial port, the only thing I cared about was "how long does it take me to get to a running proto when I am practically a newb in both languages for this application?"  And in this case, there was too much tribal knowledge assumed by the C++ camp, while Go seemed to have a shorter learning curve.  This might be completely unfair for me to put into writing, because the whole time I was following my gut - but the point is, you might be better off going into a new language if it seems to have a lot of support.  All of the languages sort of blur together with Copilot or ChatGPT writing **something** to get me started.

Okay for a little detail, the server expects routes that will be the commands sent to the Arduino stepper controller.  For example a server route of http://localhost/movr?x=10&y=20&z=30 would result in sending the Arduino a movr,10,20,30 command, waiting for it to send back OK, and then reply to the Python script that browsed to that address with an OK, and Python could move to the next movr command - and this worked out great.  Bye bye pyserial!