using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO.Ports; // No olvidar.
namespace Arduino_In_Analogico_Prueba_01_WPF
{
/// <summary>
/// Lógica de interacción para MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
// Utilizaremos un string como buffer de recepción.
string Recibidos;
SerialPort serialPort1
= new SerialPort
();
public MainWindow()
{
InitializeComponent();
// Configuramos el puerto serie.
serialPort1.BaudRate = 115200; // Baudios, tiene que ser el mismo que Arduino.
serialPort1.PortName = "COM4"; // Elegijos el mismo puerto que de Arduino.
serialPort1.Parity = Parity.None; // Nada de paridad.
serialPort1.DataBits = 8; // 8 bits.
serialPort1.StopBits = StopBits.Two; // Recomendado con 2 bits de Stop o parada.
// Abrir y mantener abierto el puerto serie mientras se ejecute la aplicación.
if (!serialPort1.IsOpen)
{
try
{
serialPort1.Open();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
// Ejecutar la función Recepción por disparo del evento ¡DataReived!
serialPort1.DataReceived += Recepcion;
}
private void Recepcion(object sender, SerialDataReceivedEventArgs e)
{
// Acumular los caracteres recibidos a nuestro "buffer" (string).
Recibidos += serialPort1.ReadExisting();
// Invocar o llamar al proceso de tramas.
this.Dispatcher.Invoke(Actualizar);
}
// Como variables de clase
private string[] Separador
= new string[] { ",",
"\r",
"\n",
"/n" }; private List
<string> Leo_Dato1
= new List
<string>();
// Procesar los datos recibidos en el bufer y extraer tramas completas.
private void Actualizar()
{
double Voltaje = 0;
double Porcentaje = 0;
// En el evento
Leo_Dato1.Clear();
Leo_Dato1.AddRange(Recibidos.Split(Separador, StringSplitOptions.RemoveEmptyEntries));
label_Lectura_Potenciometro.Content = Leo_Dato1[0].ToString();
progressBar.Value = Convert.ToInt32(Leo_Dato1[0].ToString());
double Dato_Voltaje = Convert.ToDouble(Leo_Dato1[0]);
double Dato_Porcentaje = Convert.ToDouble(Leo_Dato1[0]);
Voltaje = Dato_Voltaje * (5.00 / 1023.00);
Porcentaje = Dato_Porcentaje * (100.00 / 1023.00);
label_Voltaje.Content = Voltaje.ToString("N2") + " V.";
label_Portentaje.Content = Porcentaje.ToString("N0") + " %";
}
}
}