Python Arduino - Serial Communication

Asked

Viewed 408 times

0

How do I do Python serial communication with Arduino ? I have already used the pyserial library, but I was unable to do the communication

  • Can you put the code in the question? Pyserial works well with Arduino.

1 answer

0


Here’s a class I created to communicate via Python. With Python code just use the Arduino serial communication libraries to receive and send the data.

In the class you have the method to send a data list and to receive a data list. Now just set 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)
  • worked out, thank you very much !!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.