Hello,
I am using an Arduino Uno connected to my computer. I have programmed it to send a "hello world" message every second. On my laptop, I have a program using pyserial that should read the serial and print it. With my current code, nothing prints until I disconnect the Arduino. Then, it prints a long string with all of the "hello world"s. Can you please help me change this so it becomes Realtime?
Thanks
import serial
import time
# Initialize serial connection
arduino = serial.Serial('COM3', 9600) # Replace 'COM3' with the appropriate serial port
time.sleep(2) # Wait for 2 seconds to ensure the connection is established
while True:
if arduino.in_waiting > 0:
# Read the incoming data
data = arduino.readline().decode().strip()
print(data)
How is the Python code supposed to recognize that "Hello World" is one message?
The Arduino Serial.println() command is sending line terminators (often <CR> and <LF>, or ASCII characters standing for carriage return and line feed), so you need to learn how to write Python code that recognizes those line terminators, in order to separate individual messages.
try the following Python to receive the serial data
import serial
import time
serialPort = serial.Serial(
port="COM3", baudrate=9600, bytesize=8, timeout=2, stopbits=serial.STOPBITS_ONE
)
serialString = "" # Used to hold data coming over UART
while 1:
# Wait until there is data waiting in the serial buffer
if serialPort.in_waiting > 0:
# Read data out of the buffer until a carraige return / new line is found
serialString = serialPort.readline()
# Print the contents of the serial data
try:
print(serialString.decode("Ascii"))
except:
pass