Comunicacion serial entre Arduino y C#

En este ejemplo, la aplicación C# envia lineas al arduino, el arduino las despliega en un display lcd y luego las envia a C#, y C# las despliega en la consola:


En arduino:

void setup()
{
    Serial.begin(9600);
    incomingString = "";
}


void loop()
{
  if (Serial.available() > 0)
  {
    char incomingByte = Serial.read();  

    if (incomingByte == '\0')
    {
      disp(incomingString);

      Serial.print(incomingString);
      Serial.print('\0');
     
      incomingString = "";
    } else
        incomingString += incomingByte;  
  }
}


En C#:

        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {               
                port = new System.IO.Ports.SerialPort("COM17", 9600, System.IO.Ports.Parity.None, 8, System.IO.Ports.StopBits.One);

                port.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(port_DataReceived);
                port.Open();                
            } catch(Exception ex)
            {
                MessageBox.Show("No se pudo abrir com17: " + ex.Message);
            }
        }

        void port_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            int bytesToRead = port.BytesToRead;
            char[] z = new char[bytesToRead];
            port.Read(z, 0, bytesToRead);

            // ESTO NO VA ACA!!!!!!!  str_recibido = "";   
            //PORQUE SI VA ACA, COMO NO RECIBE TODA LA LINEA DE UN SAQUE, CUANDO VUELVE A DISPARARSE ESTE EVENTO LO PONE VACIO DE NUEVO.

            foreach (char s in z)
            {
                if (s == '\0')
                {
                    Console.WriteLine(str_recibido);
                    str_recibido = "";
                }
                else
                    str_recibido += s;
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {            
            port.Write("prueba1\0");            
            port.Write("prueba2\0");            
            port.Write("prueba3\0");            
            port.Write("prueba4\0");            
            port.Write("prueba5\0");
        }




No hay comentarios:

Publicar un comentario