2

I am trying to write a code wit pyserial (v2.6) that should wait indefinitely for any input from the port specified using inWaiting() and then read it using read() but there's no luck and no output at all. What am I doing wrong? The program just doesn't print anything at all!

Edit: both the program and the port are running on a virtual machine of Contiki OS

Edit2: z1 mote is the device connected to the port. I found out that pyserial is used to write to it (I can't upgrade pyserial to the latest version because it won't workout with the z1 motes)

The full code:

import pyserial
baudrate = 115200
port = '/dev/ttyUSB0' 
ser = serial.Serial(port,baudrate)

while 1:
    time.sleep(1)
    coming_data = ser.inWaiting()
    if coming_data != 0:
        data = ser.read(coming_data)
        print data

# the output from the port is (which should be the output of this program)
# abcd::abcd:0:0:c9 2293 6 -3 243 -23 108 
# abcd::abcd:0:0:c9 2337 8 -4 242 -27 108
Ahmed Al-haddad
  • 805
  • 2
  • 16
  • 41

1 Answers1

3

Please try this instead:

import serial
import sys
from time import sleep

try:
  ser = serial.Serial("/dev/ttyUSB0", 115200,timeout=0, parity=serial.PARITY_NONE, 
                        stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS)
except:
  sys.exit("Error connecting device")

while True:
  queue = ser.inWaiting()
  if queue > 0:
    data = ser.read(1000)
    print data
  sleep(0.2)

The problem may be related to not configuring all the UART settings as expected for the Zolertia Z1 mote.

Update: Please make sure that the connection to port is not used by another process. Because if it is printing elsewhere then it won't be able to read the data by the python script.

Ahmed Al-haddad
  • 805
  • 2
  • 16
  • 41
  • Unfortunately, I am still getting no output even when using this answer, sir. Apparently, the variable `queue` never fulfills the condition. – Ahmed Al-haddad Mar 17 '16 at 11:27
  • How are you sending the information over UART? if you use a logic anaylser are you able to see the bytes? using `make login` shows you any output? – Antonio Lignan Mar 17 '16 at 11:30
  • Yes. Using `make login` shows me the output of the `printf` statement which prints the data in this form `abcd::abcd:0:0:c9 2337 8 -4 242 -27 108 ` every few seconds. – Ahmed Al-haddad Mar 17 '16 at 11:35
  • 1
    Are you closing the `make login` process first? notice if you have the `/dev/ttyUSB0` port open elsewhere you may not see any data – Antonio Lignan Mar 17 '16 at 11:40
  • Yes. Hmm, this solved the problem. I can't believe I have been stuck here for around 1 week for this :/. Could you please indicate this in your answer so others will pick it up too hopefully. – Ahmed Al-haddad Mar 17 '16 at 11:58
  • Can someone tell me what "make login" means here. I am trying to read data from a decibel meter via serial. Getting No of bytes but nothing displaying – shadab.tughlaq Oct 05 '17 at 10:38