![]() |
serial communication write(comand) and read(result) - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: serial communication write(comand) and read(result) (/thread-8642.html) |
serial communication write(comand) and read(result) - ricardons - Mar-01-2018 Hi maybe someone could have a look at my code or suggest a better one (or another place to look for) I need to do serial communication with a device: write to device and listen to what it is saying I should write a command (send some bytes). I finish my command sendind byte 0XFF (chr(255)) 3 times in a row Then the device sends me a reply that i have to read. This reply also finishes after 3 times 0XFF I wrote this import serial ser = serial.Serial( port='/dev/ttyAMA0', baudrate=9600, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, timeout=1 ) ser.reset_output_buffer() print('Serial connected') def nxRead(value): #first i need to send a 'command' (for example 'sendme X.value' command = 'sendme X.value' ser.write(command.encode('latin-1')) ser.write(chr(255).encode('latin-1')) # 0xFF ser.write(chr(255).encode('latin-1')) # 0xFF ser.write(chr(255).encode('latin-1')) # 0xFF #by now the device should have understood my request and will send me a reply byte by byte, finishing with 0XFF 0XFF 0XFF reply = [] count =0 t3FF = False # the termination has not stopped while t3FF == False: r = ser.read().decode('latin-1) c = ord(r) reply.append(c) if c == 0xff: count = count + 1 if count == 3: t3FF = True return else: count = 0 return sIt's not working, why? RE: serial communication write(comand) and read(result) - mpd - Mar-01-2018 Be more specific. What isn't working right? Any errors or exceptions? Is it doing the wrong thing? Is it doing nothing at all? Do you know if the device is receiving your messages? I don't know this package but I know a lot of I/O libraries perform buffering, does the Serial object have a flush() method? |