title: Read and write data to/from Serial Port
body: <p>I am building a console application which will be scheduled in Task Scheduler of Windows to run my code every day at a set hour. Summing up, this application will read and write through <code>SerialPort</code>. When I send something to the Arduino, I need to receive something from it to finish up what I've sent and execute the command.</p>
  
  <p>In other words, I will send something so see if the door is opened, if it is the application will run a code to close it. If the door is already closed I will send a bunch of characters to be displayed into the Arduino Led Display.</p>
  
  <p>So I've developed a code but I am not sure if it's totally correct, if possible help me improve it. There is any changes I could make?</p>
  
  <pre><code>static void Main(string[] args)
  {
      SerialPort comport = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
      comport.Open();
  
      string start = "?";
      string carriageReturn = "\r";
      string text = string.Empty;
  
      string mensage = "@" + "r" + "\r";
      string mensage2 = "@" + "{" + texto + "\r";
  
      try
          {
              while (true)
              {
                  //Send to the Arduino
                  comport.Write(start+ "*" + carriageReturn);
  
                  //If the serial port have bytes to read
                  if (comport.BytesToRead &gt; 0)
                  { 
                      //Buffer with data
                      byte[] dados = HexStringToByteArray(mensage);
  
                      //Handle data
                      comport.Read(dados, 0, dados.Length);
  
                      //Send again to execute the the command
                      comport.Write(start + "*" + carriageReturn);
                  }
  
                  if (comport.BytesToRead &gt; 0)
                  { 
                      comport.Write(start + "*" + carriageReturn);
  
                      byte[] dados2 = HexStringToByteArray(mensage2);
  
                      comport.Read(dados2, 0, dados2.Length);
  
                      comport.Write(text);
                  }
                  comport.Close();
              }
          }
  
          catch(Exception ex)
          {
          }
  }
  
  private static byte[] HexStringToByteArray(string s)
  {
      s = s.Replace(" ", "");
      byte[] buffer = new byte[s.Length / 2];
  
      for (int i = 0; i &lt; s.Length; i += 2)
          buffer[i / 2] = (byte)Convert.ToByte(s.Substring(i, 2), 16);
          return buffer;
  }
  </code></pre>
  
  <p><strong>EDIT:</strong></p>
  
  <p>My basic input output mapping/relationship is:</p>
  
  <p>I will send <code>?*\r</code> to the Arduino, then I will wait for a answer. </p>
  
  <p><strong>If</strong> the answer from Arduino is <code>@r\r</code> I will send the <code>?*\r</code> again. </p>
  
  <p><strong>If</strong> the answer from the Arduino is <code>@{/r</code> I will send a string to him. </p>