Pregunta

I am running my LX terminal on my Debian installed Raspberry Pi. I have a PLC connected by USB to my Raspberry Pi. I want to send ASCII using python from my terminal I even installed Python Serial but I dont know how to use it. This is the code I have been trying in python. I know the serial port works since I used Linux based minicom to send dsata to plc and it worked. today with python it isnt working the ay i want it to

user ~$ python

>>>import serial
>>>ser =  serial.Serial('/dev/ttyUSB0')
>>>ser.portstr
'/dev/ttyUSB0'
>>>ser

What have I been doing wrong? Any help will be appreciated

¿Fue útil?

Solución

import serial
ser =  serial.Serial('/dev/ttyUSB0', 4800)
while 1:
    inp = raw_input("Enter the data to send or enter 'exit' to exit:")
    if inp=='exit':
        break
    else:
        ser.write(inp)

This piece of code communicates with ttyUSB0 at baudrate 4800. Make sure you are writing at baudrate which is same as that at which your listener is configured to listen at.

It takes a user input as string and sends it through serial. This happens in a loop till exit is entered by the user.

Also make sure that you are running only one process to read from serial on the listening end, or only one of them will read from the serial or both of them will read parts of it.

Hope this helps :)

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top