I use this kind of Python code to receive command lines from my Arduino
#!/usr/bin/python3
# ============================================
# KEEP THIS INFORMATION IF YOU USE THIS CODE
#
# code is placed under the MIT license
# Copyright (c) 2019 J-M-L For the Arduino Forum
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
# ===============================================
import sys, threading, queue, serial
arduinoPort = '/dev/cu.usbserial-0001'
baudRate = 115200
arduino = serial.Serial(arduinoPort, baudrate=baudRate, timeout=.1)
arduinoQueue = queue.Queue()
def listenToArduino(commandQueue):
message = b''
while True:
incoming = arduino.read()
if (incoming == b'\n'):
arduinoQueue.put(message.decode("utf-8").strip().upper())
message = b''
else:
if (incoming != b''):
message += incoming
def configure():
arduinoThread = threading.Thread(target=listenToArduino, args=(arduinoQueue,))
arduinoThread.daemon = True
arduinoThread.start()
# ---- MAIN CODE -----
configure()
print("Ready to receive input from " + arduinoPort)
currentCommand = ""
while True:
if not arduinoQueue.empty():
currentCommand = arduinoQueue.get()
print("Got [" + currentCommand + "]")
you need to adjust
arduinoPort = '/dev/cu.usbserial-0001'
to match your settings
you can try the code with this Arduino code
unsigned long count = 0;
void setup() {
Serial.begin(115200); Serial.println();
}
void loop() {
Serial.print("count=");
Serial.println(count++);
delay(random(500, 2001));
}
the idea is to receive the lines in a dedicated thread and store the messages in a queue. the main code will get the messages out of the queue and handle them (here just printing). This way if the handling part is long, you keep listening in the background to what's coming from the Arduino Side and buffer it into the queue
PS/ remove the .upper()
if you want to get the original string as it was sent and not all in upper capitals