Arduino serial port with C #

0

I get the information passed through the serial port of my arduino with this code:

cnx.Open();
    string carro = cnx.ReadLine();
    textBox1.Text = carro;
    cnx.Close();

I would like to know if it would be possible for me to give two arduino print and send two values to the serial port with different information? and how would I get these two information with readline in my C # program?

    
asked by anonymous 11.04.2017 / 18:29

2 answers

1

You can write to a Print only, and separate it by a common character, for example a ';' it would look like this:

arduino sends: "ABC-1234; GM; CELTA; WHITE"

In C #:

string linha = cnx.ReadLine();
string[] valores = linha.Split(';');

string placa = valores[0]; //ABC-1234
string marca = valores[1]; //GM
string modelo = valores[2]; //CELTA
string cor = valores[3]; //BRANCO

As I understand, this is what you need

    
11.04.2017 / 21:59
2

You could read the serial port information with ReadLine() , but you would need to create a listener so that every time you had data available on the port, they were read.

The suggestion is that you use the event DataReceived , which will be called when data is being read *.

For testing, you can upload the program SerialEvent of Arduino:

Andwiththefollowingexamplecode,youcansendandreceivedatathroughtheserialport:

usingSystem;usingSystem.IO.Ports;namespaceArduinoSerial{classArduinoSerial{privatestaticSerialPortportaSerial=newSerialPort("COM3",
            9600, Parity.None, 8, StopBits.One);

        static void Main(string[] args)
        {
            // quando há dados na porta, chamamos dadosRecebidos
            portaSerial.DataReceived += new SerialDataReceivedEventHandler(dadosRecebidos);

            // criar a conexão
            portaSerial.Open();

            // mantendo o programa rodando
            while (portaSerial.IsOpen)
            {
                // o que escrevermos no console, vai pra porta serial
                portaSerial.WriteLine(Console.ReadLine());
            }
        }

        // dadosRecebidos imprime a informação de volta no console
        static void dadosRecebidos(object sender, SerialDataReceivedEventArgs e)
        {
            SerialPort sp = (SerialPort)sender;
            string dados = sp.ReadLine();
            Console.WriteLine(dados);
        }
    }
}

Result:

  

IntheSerialEventprogramoftheArduino,youwillseethattosenddata  forserialport,Serial.println(inputString);isused.Modifying  theprogram,andreplacinginputStringwithwhateveryouwant,you  youcansenddifferentdatatoyourC#program.

*Inthedocumentationwhatisactuallyindicatedistouse BytesToRead to see if there is data to be read.

Sources:
How to Read and Write from the Serial Port
Server Client send / receive simple text
C # Serial Port Listener

    
11.04.2017 / 21:03