简体   繁体   中英

Pyserial serial.write() doesn't work

I need to communicate with an Arduino. Doing serial.readline() to read what Arduino has to say works fine. Doing serial.write('something') doesn't seem to do anything.

What is interesting is that if I write the same code in the console or command-line, it works as expected...

Using Python 2.7.

Python code:

import time
import serial

# setup Arduino USB communication
try:
    arduinoSerialData = serial.Serial('com3', 9600)

except: # not connected/damaged
    pass

while True:
    if arduinoSerialData.inWaiting() > 0:
        arduinoSerialData.write('A')
        arduinoSerialData.flush()
        datastr = arduinoSerialData.readline()
        print datastr
        time.sleep(1)

I know I´ma little bit too late but today I had the same problem with Pyserial and an ESP32, a device sort of like an arduino. The solution was to give pyserial the same configuration as the serial interface in the ESP32:

esp = serial.Serial("COM10", 115200)
esp.parity=serial.PARITY_EVEN
esp.stopbits=serial.STOPBITS_ONE
esp.bytesize=serial.EIGHTBITS

I send the commands like this:

arr = [32,2,0,4] #Decimal
esp.write(arr)

This is the ESP32 configuration, in case you need to know:

uart_config_t uart_config = {
        .baud_rate = 115200,
        .data_bits = UART_DATA_8_BITS,
        .parity    = UART_PARITY_EVEN,
        .stop_bits = UART_STOP_BITS_1,
        .flow_ctrl = UART_HW_FLOWCTRL_DISABLE
};
    
uart_param_config(UART_PORT_NUM, &uart_config);

The ESP now echoes the command correctly I hope this can help.

try to add the timeout parameter in the Python script, then try to set your main arduino code in a while loop step1: python

 arduinoSerialData = serial.Serial('com3', 9600, 1)

replace the arduinoSerialData.flush() by:

 arduinoSerialData.flushInput()

step2: Arduino:

void loop(){
    while (Serial.available > 0){
            // your main code
    }
}

打开端口后放置time.sleep(2)行,以便给Arduino时间重新启动。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM