Abrir Puerto Serial c# y DataReceived

El siguiente código fuente muestro como conectarnos a un puerto serial "COM1" y leer datos escritos en el por medio del evento DataReceived.

 

private System.IO.Ports.SerialPort RS232 = new System.IO.Ports.SerialPort();

// Recibir tramas por el puerto serial

void RS232_DataReceived(object sender, SerialDataReceivedEventArgs e) {

System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();

try

{

this.Invoke(new EventHandler(RS232_READ));

}

catch (Exception ex)

{

MessageBox.Show(ex.Message);

}

}

//  Invocamos este metodo para leer la ultima trama recibida en el puerto

void RS232_READ(object s, EventArgs e) {

try

{

System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();

string strUltimaTrama = "";

char[] splitter = { };

strTramaDevuelta = strTramaDevuelta + RS232.ReadExisting();

}

catch (Exception ex)

{

MessageBox.Show(ex.Message);

}

}

 

// Abrir puerto Serial

private bool AbrirPuertoSerial()

{

if (RS232.IsOpen)

RS232.Close();

//deshabilitar controles

tsbtnOpen.Enabled = true;

string SelectedPort = "Com1";

try

{

string BaudRate = System.Configuration.ConfigurationManager.AppSettings["BautRate"].ToString();

RS232 = new SerialPort(SelectedPort, Convert.ToInt16(BaudRate), Parity.None, 8, StopBits.One);

RS232.DataReceived += new SerialDataReceivedEventHandler(RS232_DataReceived);

RS232.DtrEnable = true;

RS232.RtsEnable = true; // RTS request to sent 

RS232.Encoding = Encoding.ASCII; //System.Text.Encoding.GetEncoding(28591);

RS232.ReadTimeout = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["TimeOut"].ToString());

RS232.StopBits = StopBits.One; // bits de parada

RS232.DataBits = 8; // longitud de data bits

RS232.Parity = Parity.None; // parity checking protocol

RS232.Handshake = Handshake.None;

RS232.BaudRate = Convert.ToInt32(BaudRate);

RS232.DiscardNull = false;

RS232.NewLine = "";

//RS232.ReadBufferSize = 4098;

RS232.Open();

return true;

}

catch (IOException)

{

return false;

}

catch (UnauthorizedAccessException)

{

return false;

}

catch (Exception)

{

return false;

}

}

About omaracostacasas

ING SOFTWARE
This entry was posted in Microsoft .NET. Bookmark the permalink.

Leave a comment