TboneH
TboneH

Reputation: 51

PySerial slowdown on read from Arduino

I'm attempting to write a handshaking procedure to allow my python program to automatically detect which port the Arduino is on. It works, however sometimes it runs extremely slow. Here's the problematic part of my code:

import serial, serial.tools.list_ports, time

portList = list(serial.toools.list_ports.comports())
conn = 0
while conn == 0:
    for port in portList:
        print(port[0])
        try:
            arduino = serial.Serial(port[0], 4800, timeout=.1)
            time.sleep(.2)
            sig = arduino.read()
            signum = int.from_bytes(sig, byteorder='little')
            if signum == 7:
                global comport
                comport = port[0]
                conn = 1
                break
        except:
            print('Could not read from ' + str(port[0]))

Essentially I have the Arduino constantly sending the arbitrary number '7' to the serial port. The python script scans each port for a 7 until it finds it. What's happening is that when it gets to the port that the Arduino is on, the code seemingly pauses executing for about 10 seconds at the arduino = serial.Serial(...) line right underneath the try statement. Since it's in a try loop, I know it's not throwing an error because it does eventually make it through. Is it just having trouble opening the port? How can this be fixed? I am on Python 3.4.3 and pySerial 2.7.

Upvotes: 1

Views: 297

Answers (2)

Joran Beasley
Joran Beasley

Reputation: 113978

I think the issue is more with how arduino does serial ... it waits for a serial connection to open then it does a bunch of setup you can see this with a relatively simple arduino sketch

int i;
void setup(){
   i=8;
   Serial.begin(9600);
}
void loop(){
   Serial.print(i);
   Serial.print(",");
   i+=1;
}

and I think that you will always see 8 as the first number when you connect to the port ... I dont have an arduino on hand but I seem to recall seeing this behaviour

Upvotes: 1

Matt
Matt

Reputation: 11

Just to check: Is the baudrate the same for both your Arduino and Python? Are there any other programs trying to access the Arduino?

Upvotes: 0

Related Questions