evan
evan

Reputation: 189

Pyserial is not opening a serial port when it is called to do so

When I open a serial port it won't subsequently remain open to send data. The code works when I call it before running the gui but when I redo the commands in a callable function, I cannot send the data.

def connect(self):
    try:
        port_loc = self.builder.get_variable('port_location')
        port = port_loc.get()
        print(port)

        #baud = self.builder.get_variable('baudrate_entry')
        #baurdate = baudrate_entry.get()
        #baudrate = int(baudrate)
        #time = timeout_entry.get()
        ser = serial.Serial(port, baudrate = 9600)
        if ser.isOpen()==True:
            time.sleep(0.5)
            print('The Arduino is Connected')
    except:
        print("Error: Could not connect to Arduino. Try changing device location or baudrate")

When I use this command, I get an output of

/dev/ttyACM0
The Arduino is Connected

When I attempt to send files, I get the following.

Error: Data not sent

Therefore, The serial port is connected but I cannot send data over that same port

def send_data1(self):
    # import data from entry widgets
    dist1val = self.builder.get_variable('motor1_dist_entry')
    dist1 = dist1val.get()
    dist1 = int(dist1)

    accel1val = self.builder.get_variable('motor1_accel_entry')
    accel1 = accel1val.get()
    accel1 = int(accel1)

    speed1val = self.builder.get_variable('motor1_speed_entry')
    speed1 = dist1val.get()
    speed1 = int(speed1)

    dist2 = 0


    data = struct.pack("!llhhhh", dist1, dist2, speed1, dist2, accel1, dist2)
    try:
        ser.write(data)
    except:
        print("Error: Data not sent")

I am using Pygubu for the gui.

Upvotes: 0

Views: 1634

Answers (1)

evan
evan

Reputation: 189

My error was only calling the serial port inside the function. When the function ended, the serial port was no longer open to send data. To remedy the situation I made ser a global variable.

in the connect(self) function call the ser variable as global by:

def connect(self):
    try:
        port_loc = self.builder.get_variable('port_location')
        port = port_loc.get()
        print(port)

        #baud = self.builder.get_variable('baudrate_entry')
        #baurdate = baudrate_entry.get()
        #baudrate = int(baudrate)
        #time = timeout_entry.get()

        global ser

        ser = serial.Serial(port, baudrate = 9600)
        if ser.isOpen()==True:
            time.sleep(1)
            print('The Arduino is Connected')
    except:
        print("Error: Could not connect to Arduino. Try changing device location or baudrate")

The global ser makes the code work.

Upvotes: 1

Related Questions