Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Writing to and Reading from serial port

I've read the documentation, but can't seem to find a straight answer on this. I have a list of all COM Ports in use by Modems connected to the computer. From this list, I try to open it, send it a command, and if it says anything back, add it to another list. I'm not entirely sure I'm using pyserial's read and write functions properly.

i=0
for modem in PortList:
    for port in modem:
        try:
            ser = serial.Serial(port, 9600, timeout=1)
            ser.close()
            ser.open()
            ser.write("ati")
            time.sleep(3)
            print ser.read(64)
            if ser.read(64) is not '':
                print port
        except serial.SerialException:
            continue
        i+=1

I'm not getting anything out of ser.read(). I'm always getting blank strings.

like image 400
RageCage Avatar asked Oct 02 '13 17:10

RageCage


People also ask

Can you read and write from the same serial port?

You can indeed simultaneously read and write through the serial port. At the hardware level, the serial port (the UART) is a transmitter and a receiver, which are almost independent. At the software level, they are both handled through interrupts that read from / write to a software buffer.

How do you send data to a serial port in Python?

Transmitting Data: Firstly, we need to include the serial library. We can then declare an instance of the serial port and add the SerialPort, baudRate and timeOut parameters , I'm using serial0, 115200 and 0.050. To find your Pi serial port use the command 'lsdev'. In my case, my serial port was serial0.

How data transfer from and to serial port?

To transmit a data byte, the serial device driver program sends a data to the serial port I/O address. This data gets into a 1-byte "transmit shift register" in the serial port. From this shift register bits are taken from the data one-by-one byte and sent out bit-by-bit on the serial line.


2 Answers

a piece of code who work with python to read rs232 just in case somedoby else need it

ser = serial.Serial('/dev/tty.usbserial', 9600, timeout=0.5)
ser.write('*99C\r\n')
time.sleep(0.1)
ser.close()
like image 186
PHMADEIRA Avatar answered Oct 06 '22 01:10

PHMADEIRA


ser.read(64) should be ser.read(size=64); ser.read uses keyword arguments, not positional.

Also, you're reading from the port twice; what you probably want to do is this:

i=0
for modem in PortList:
    for port in modem:
        try:
            ser = serial.Serial(port, 9600, timeout=1)
            ser.close()
            ser.open()
            ser.write("ati")
            time.sleep(3)
            read_val = ser.read(size=64)
            print read_val
            if read_val is not '':
                print port
        except serial.SerialException:
            continue
        i+=1
like image 23
Chaosphere2112 Avatar answered Oct 05 '22 23:10

Chaosphere2112