How do I do Python serial communication with arduino? I have already made use of the pyserial library, but I could not make the communication
How do I do Python serial communication with arduino? I have already made use of the pyserial library, but I could not make the communication
Here is a class I created to communicate via Python. With the Python code, you just have to use Arduino's serial communication libraries to receive and send data.
In the class you have the method to send a list of data and to receive a list of data. Now just define your communication protocol as: buffer size, header, checksum, according to your need!
import serial
class Comunicacao():
def SerialInit(self, NomePorta, Velocidade, TimeRX, TimeTX):
try:
self.PortaCom = serial.Serial(NomePorta, Velocidade, 8, serial.PARITY_NONE, serial.STOPBITS_ONE, TimeRX,
False, False, False, TimeTX)
self.PortaCom.reset_input_buffer()
self.PortaCom.reset_output_buffer()
except Exception:
print("Erro na porta " + NomePorta + "!")
def WriteSerial(self, DadosTx):
try:
self.PortaCom.flushOutput()
TamPac = DadosTx[3]
for i in range(TamPac):
DadoTxByte = bytes((DadosTx[i],))
self.PortaCom.write(DadoTxByte)
print(DadoTxByte)
except Exception:
print("Erro Escrita")
def Leitura_Serial(self, DadosRx):
LeituraSerial = [0] * 200
for i in range(200):
if (self.PortaCom.in_waiting > 0):
LeituraSerial[i] = self.PortaCom.read()
LeituraSerial[i] = self.ByteToInt(LeituraSerial[i])
print(LeituraSerial[i])
else:
break
DadosTx = [1,2,3,4,5,6,7,8]
DadosRx = [0] * 100
PortaCom = Comunicacao()
PortaCom.SerialInit("/dev/ttyUSB0", 115200, 1, 1)
PortaCom.WriteSerial(DadosRx)