using System;
using System.IO.Ports;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace Velocímetro_Arduino_Puerto_serie_01
{
public partial class Form1 : Form
{
// Utilizaremos un string como buffer de recepción.
string recibidos;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// Añado los puertos disponible en el PC con SerialPort.GetPortNames() al comboBox_Puerto.
try
{
comboBox_Puerto.DataSource = SerialPort.GetPortNames();
}
catch
{
MessageBox.Show("No encuentra ningún puerto físico ni virtual.", "Aviso:",
MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
// // Añade puertos disponibles físicos y virtuales.
serialPort1.PortName = comboBox_Puerto.Text.ToString();
}
#region Funciones.
void UsbConectado()
{
byte[] miBuffer = Encoding.ASCII.GetBytes("USB_CONECTADO");
serialPort1.Write(miBuffer, 0, miBuffer.Length);
}
void UsbDesconectado()
{
byte[] miBuffer = Encoding.ASCII.GetBytes("USB_DESCONECTADO");
serialPort1.Write(miBuffer, 0, miBuffer.Length);
}
// Detecta USB o puerto serie virtual cuando lo conecta y desconecta del cable.
protected override void WndProc(ref Message USB)
{
if (USB.Msg == 0x219)
{
comboBox_Puerto.DataSource = SerialPort.GetPortNames();
}
// Detecta si hay cambios en el usb y si los hay los refleja.
base.WndProc(ref USB);
}
// Procesar los datos recibidos en el buffer y extraer las tramas completas.
void Actualizar(object sender, EventArgs e)
{
// Asignar el valor de la trama al label_Recibir_Km.
label_Recibir_Km.Text = recibidos;
switch (recibidos)
{
case "OK":
byte[] miBuffer = Encoding.ASCII.GetBytes("Conectado. ");
serialPort1.Write(miBuffer, 0, miBuffer.Length);
label_Recibir_Km.Text = "Arduino conectado.";
break;
default:
break;
}
// Limpiar.
recibidos = "";
}
#endregion
#region Botones.
private void button_Conectar_Click(object sender, EventArgs e)
{
try
{
serialPort1.PortName = comboBox_Puerto.Text.ToString(); // Puerto seleccionado previamente.
serialPort1.Open(); // Abrir puerto.
UsbConectado();
comboBox_Puerto.Enabled = false;
comboBox_Baudios.Enabled = false;
button_Conectar.Enabled = false;
button_Desconectar.Enabled = true;
button_Enviar.Enabled = true;
}
catch
{
MessageBox.Show("El puerto no existe.", "Aviso:",
MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
private void button_Desconectar_Click(object sender, EventArgs e)
{
UsbDesconectado();
serialPort1.Close(); // Cerrar puerto.
comboBox_Puerto.Enabled = true;
comboBox_Baudios.Enabled = true;
button_Conectar.Enabled = true;
button_Desconectar.Enabled = false;
button_Enviar.Enabled = false;
}
private void button_Enviar_Click(object sender, EventArgs e)
{
byte[] miBuffer = Encoding.ASCII.GetBytes("KM" + textBox_Km.Text);
serialPort1.Write(miBuffer, 0, miBuffer.Length);
}
#endregion
// Al cerrar el formulario, cierra el puerto si está abierto.
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
try
{
// Al cerrar este programa, indica a Arduino cerrado.
// Arduino sigue con su rutina al detectar CERRADO.
byte[] miBuffer = Encoding.ASCII.GetBytes("C#_CERRADO");
serialPort1.Write(miBuffer, 0, miBuffer.Length);
// Cerrar puerto.
serialPort1.Close();
}
catch (Exception error)
{
MessageBox.Show(error.Message, "Aviso:",
MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
// Acumula los caracteres recibidos a nuestro "buffer" string.
recibidos += serialPort1.ReadExisting();
// Invocar o llamar al proceso de tramas.
Invoke
(new EventHandler
(Actualizar
)); }
}
}