-1

I want to send commands to an Arduino and I want to get the Answers with serial readline(). That works fine when I try it in the inline console of Python. But when I do it in a script like here:

    import serial
    import time

    ser=serial.Serial('/dev/ttyACM0',9600)



   ser.write("T")
   time.sleep(0.5)
   print ser.readline()

  ser.write("5")
  time.sleep(0.5)
  print ser.readline()

  ser.write("0")
  time.sleep(0.5)
  print ser.readline()

  ser.write("0")
  time.sleep(0.5)
  print ser.readline()

  ser.write("0")
  time.sleep(0.5)
  print ser.readline()


  ser.write("0")
  time.sleep(0.5)
  print ser.readline()


  ser.write("0")
  time.sleep(0.5)
  print ser.readline()


  ser.write("R")
  time.sleep(0.5)


  ser.write("M")
  time.sleep(0.5)

the program stops at the first readline() function

wwii
  • 23,232
  • 7
  • 37
  • 77
jofri
  • 131
  • 1
  • 16
  • 3
    serial communication is blocking. In other words, your python code will wait and only resume once Arduino has said something. http://stackoverflow.com/questions/17553543/pyserial-non-blocking-read-loop – dodell Jan 13 '17 at 14:09

1 Answers1

1

readline() usually waits for string termination character, such as \r, \n, or \r\n. write() in most cases also does require this character. Since your code works from console, add \n to the end of strings to send. If \n doesn't work, try \r or \r\n.

ser.write("T\n")
time.sleep(0.5)
print ser.readline()

Alternatively, you can read lines this way:

s = ''
while ser.inWaiting():
    s += ser.read()
print s