0
votes

I have an Arduino UNO and I am communicating serially with my PC and the UNO. I am using pyserial to communicate with the the UNO and I am receiving only the first character of the string that I sent to my microcontroller. Below is the script for serial communication:

import serial
import time
port = "\\.\COM4"
baudrate = 19200
parity=serial.PARITY_NONE
no=serial.EIGHTBITS
stopbits= serial.STOPBITS_ONE

ser=serial.Serial()
ser.port=port
ser.baudrate=baudrate
ser.timeout=1
ser.parity=parity
ser.bytesize=no
ser.stopbits=stopbits
ser.open()
time.sleep(1)
time.sleep(1)
ser.setDTR(level=0)
time.sleep(1)
ser.write("Hello World");
bytes=ser.read()
print bytes,
ser.close()

I have set up my microcontroller to echo whatever has been sent to it and my program exits without printing the string "Hello World". It does, however, print the first character 'H'. Is there a problem with my script? I checked my microcontroller code using the Arduino Serial Monitor and it echos the output just fine when I send data via the monitor. What is wrong with this code? Why doesn't my code print the entire string but only the first letter of the string I pass to the ser.write() method? Thanks in advance for your replies!

1
Are you sure you've read everything that is being sent back? - Ignacio Vazquez-Abrams
When receiving, you need to what until all the response has arrived. That could be by waiting for a specific number of characters, or by waiting until no character has been received for a certain (relatively long) amount of time. At a baud rate of 19200, how long does each character take to transmit/receive? - balmy
Should my timeout be set according to the number of characters that I have sent or should I implement a loop that checks if bytes == "Hello World" and breaks if it is? I do not see any point in implementing the loop as the purpose of this script is to communicate with the UNO irrespective of the data exchanged. - physio

1 Answers

1
votes

ser.read() takes an integer number of bytes to read as an argument, so to read something like "Hello World," you'll need to modify your command to be ser.read(15).