Ver Mensaje Individual
  #3 (permalink)  
Antiguo 10/11/2008, 09:47
jhansen
 
Fecha de Ingreso: noviembre-2008
Mensajes: 6
Antigüedad: 15 años, 6 meses
Puntos: 0
De acuerdo Respuesta: Leer el puerto serie desde .net

Hola mi nombre es JHANSEN DEIBY CHAVEZ MESTANZA
espero que te sirva de algo este codigo

// Proyecto : CPuertoSerie
// Nombre : Form1 : Form
// Tipo : Clase
// Clase : Form1
// Creado : 24.01.2007
// Autor : Pep Lluis
// Version : 1.0
//
// * AVISO IMPORTANTE * Este programa es propiedad (c)2007 Pep Lluis Bano.
// * AVISO IMPORTANTE * Se autoriza su uso, solo con fines formativos.
//
// EL USO DE ESTA APLICACION IMPLICA LA ACEPTACION DE LAS CONDICIONES DE USO QUE SE APLICAN
// AL PROGRAMARIO "Open Source", ESTE PROGRAMA SE PROPORCIONA "COMO ESTA", NO OBLIGANDO AL
// AUTOR A CONTRAER COMPROMISO ALGUNO PARA CON QUIENES LO UTILICEN, ASI COMO DECLINANDO
// CUALQUIER REPONSABILIDAD DIRECTA O INDIRECTA, CONTRAIDA POR LOS MISMOS EN SU UTILIZACION
// FUERA DE LOS PROPOSITOS PARA EL QUE FUE ESCRITO Y DISEÑADO.
//
// CUALQUIER MODIFICACIÓN Y DISTRIBUCION DEL MISMO DEBERA CONTENER Y CITAR SU FUENTE Y ORIGEN.
//
// ASI MISMO EL AUTOR AGRADECERA CUALQUIER COMENTARIO o CORRECCION QUE LOS LECTORES ESTIMEN
// OPORTUNA CONTRIBUYENDO ESTOS ULTIMOS A MEJORAR LA APLICACION SOLO CON FINES FORMATIVOS.
// CONSIDEREN ENVIAR SUS COMENTARIOS A : [email protected]
// --------------------------------------------------------------------------------------------

using System;
using System.Windows.Forms;

// Ejemplo para la lectura de tramas del puerto serie.
// Insertando un conector puenteando el pin 2 y 3 del puerto serie
// podremos simular envio/recepcion de tramas, usando el Button1/2

namespace PuertoSerie
{
public partial class Form1 : Form
{
// Utilizaremos un string como buffer de recepcion
string Recibidos;

public Form1()
{
InitializeComponent();
// Ejecutar la funcion Recepcion por disparo del Evento 'DataReived'
this.serialPort1.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(thi s.Recepcion);
}

// Al cargar el form
private void Form1_Load(object sender, EventArgs e)
{
// Abrir el puerto de comunicaciones
this.serialPort1.BaudRate = 19200;
this.serialPort1.PortName = "COM1";
this.serialPort1.Open();
this.Text = this.serialPort1.PortName +":"+ this.serialPort1.BaudRate;
}

// Al recibir datos
private void Recepcion(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
// Acumular los caracteres recibidos a nuestro 'buffer' (string)
Recibidos += this.serialPort1.ReadExisting();
// Invocar al proceso de tramas
this.Invoke(new EventHandler(Actualizar));
}

// Procesar los datos recibidos en el buffer y extraer tramas completas
// El caracter 0x01 identifica el Inicio de una trama y el 0x3f el final
private void Actualizar(object s, EventArgs e)
{
int Inicio = Recibidos.IndexOf("\x01"); // Posicion de Inicio de trama
int Final = Recibidos.IndexOf("\x3f"); // Posicion de Final de trama
string BufferResultante = ""; // Buffer resultante
//
// Si exiset posicion de inicio y una despues del final
if ((Inicio > -1) & (Final > Inicio))
{
// Covertir la trama en un array de char's
char [] miTrama = Recibidos.Substring(Inicio, Final+1).ToCharArray();
// Eliminar la trama procesada del buffer
BufferResultante = Recibidos.Substring(Final, Recibidos.Length - (Final + 1));
Recibidos = BufferResultante;
// Descomponer los bytes recibidos y componer una linea con sus valores en Hex
string miTramaEnHex = "";
foreach(Byte info in miTrama)
{
miTramaEnHex+=@"0x"+Convert.ToString(info,16)+" ";
}
// Añadir a linea a la lista de tramas recibidas
this.listBox1.Items.Add(miTramaEnHex);
}
else
// De no cumplirse las condiciones de Inicio/Fin
{
// Si existe final
if (Final > -1)
{
// Eliminar bytes con un 0x3f detras y sin 0x01 delante
if (Final + 1 < Recibidos.Length)
{
BufferResultante = Recibidos.Substring(Final + 1, Recibidos.Length);
}
// El final esta en la ultima posicion
else
{
BufferResultante = "";
}

Recibidos = BufferResultante;
this.listBox1.Items.Add("Trama sin formato!!" + Convert.ToString(Final+1)+"Bytes eliminados");
}
}
// Visualizar el buffer pendiente de procesar
char[] actual = Recibidos.ToCharArray();
label1.Text = "";
foreach (Byte Bite in actual)
{
label1.Text += @"0x" + Convert.ToString(Bite, 16) + " ";
}
}

private void button1_Click(object sender, EventArgs e)
{
// Enviar trama Correcta
byte[] miBuffer = new byte[16];
miBuffer[0] = 0x01;
miBuffer[1] = 0x20;
miBuffer[2] = 0x21;
miBuffer[3] = 0x22;
miBuffer[4] = 0x23;
miBuffer[5] = 0x24;
miBuffer[6] = 0x25;
miBuffer[7] = 0x26;
miBuffer[8] = 0x27;
miBuffer[9] = 0x28;
miBuffer[10] = 0x29;
miBuffer[11] = 0x2A;
miBuffer[12] = 0x2B;
miBuffer[13] = 0x2C;
miBuffer[14] = 0x2D;
miBuffer[15] = 0x3f;
this.serialPort1.Write(miBuffer, 0, miBuffer.Length);
}

private void button2_Click(object sender, EventArgs e)
{
// Enviar trama incorrecta
byte[] miBuffer = new byte[10];
miBuffer[1] = 0x20;
miBuffer[2] = 0x21;
miBuffer[3] = 0x22;
miBuffer[4] = 0x23;
miBuffer[5] = 0x24;
miBuffer[6] = 0x25;
miBuffer[7] = 0x2C;
miBuffer[8] = 0x2D;
miBuffer[9] = 0x3f;
this.serialPort1.Write(miBuffer, 0, miBuffer.Length);
}

}
}