Pyserial未在调用时打开串口。

2024-09-28 20:50:46 发布

您现在位置:Python中文网/ 问答频道 /正文

当我打开一个串行端口,它将不会继续保持开放发送数据。当我在运行gui之前调用它时,代码可以工作,但是当我在可调用函数中重做命令时,我不能发送数据。你知道吗

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")

当我使用这个命令时,我得到

/dev/ttyACM0
The Arduino is Connected

当我试图发送文件时,我得到以下信息。你知道吗

Error: Data not sent

因此,串行端口已连接,但我无法通过同一端口发送数据

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")

我正在使用Pygubu作为gui。你知道吗


Tags: 端口selfgetportbuildervariable发送数据int
1条回答
网友
1楼 · 发布于 2024-09-28 20:50:46

我的错误只是调用函数中的串行端口。当函数结束时,串行端口不再打开以发送数据。为了纠正这种情况,我将ser作为一个全局变量。你知道吗

在connect(self)函数中,通过以下方式将ser变量作为全局变量调用:

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")

全局ser使代码工作。你知道吗

相关问题 更多 >