No lee el puerto serie
Publicado por Meta (138 intervenciones) el 20/04/2021 17:34:07
Hola:
Estoy recibiendo datos por el puerto serie por cada 100 ms, de 0 a 1024 en decimal.
El programa no lee nada, no muestra nada en pantalla. Tiene que mostrar valores de al 1024, porcentaje del 0 % al 100 % con su barra de dibujo y voltaje del 0 al 5 voltios. La pantalla en consola muestra todo en negro.
Dejo aquí el código.
Saludos.
Estoy recibiendo datos por el puerto serie por cada 100 ms, de 0 a 1024 en decimal.
El programa no lee nada, no muestra nada en pantalla. Tiene que mostrar valores de al 1024, porcentaje del 0 % al 100 % con su barra de dibujo y voltaje del 0 al 5 voltios. La pantalla en consola muestra todo en negro.
Dejo aquí el código.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
using System;
using System.IO.Ports; // No olvidar.
using System.IO;
using System.Collections.Generic;
namespace Porcentaje_Barra_Puerto_Serie_Consola_02
{
class Program
{
public static string Recibidos = "";
// Como variables de clase
public static string[] Separador = { ",", "\r", "\n" };
public static List<string> Leo_Dato = new List<string>();
public static SerialPort serialPort1;
static void Main(string[] args)
{
Console.Title = "Serial Port C#";
// string Enviar_datos = "";
int variarEsteValor = 0; // De 0 a 1023.
double resultadoPorcentaje = 0;
double resultadoVoltios = 0;
double mitadBarra = 0;
// Crear un nuevo objeto SerialPort con la configuración predeterminada.
serialPort1 = new SerialPort
{
// Configuración del puerto serie.
BaudRate = 9600, // Baudios o velocidad. 115200
PortName = "COM4", // Número del puerto serie.
Parity = Parity.None, // Sin paridad.
DataBits = 8, // 8 Bits de datos.
StopBits = StopBits.Two, // Bits de parada.
Handshake = Handshake.None, // Control de flujo.
ReadBufferSize = 4096, // Tamaño del Búffer de lectura en Bytes.
WriteBufferSize = 2048, // Tamaño del Búffer de escritura en Bytes.
//ReadTimeout = 500, // Establecer lectura de espera.
WriteTimeout = 500, // Establecer escritura de espera.
DtrEnable = false,
RtsEnable = false
};
try
{
serialPort1.Open();
}
catch (IOException)
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.CursorVisible = false;
Console.SetCursorPosition(25, 12);
Console.WriteLine("El puerto " + serialPort1.PortName + " no existe.");
}
serialPort1.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
while (true)
{
// En el evento
Leo_Dato.Clear();
Leo_Dato.AddRange(Recibidos.Split(Separador, StringSplitOptions.RemoveEmptyEntries));
if (string.IsNullOrEmpty(Recibidos)) continue;
variarEsteValor = Convert.ToInt32(Recibidos); // Almacena los datos introducidos en consola a la variable.
Console.WriteLine(); // Salto de línea.
Console.WriteLine();
resultadoPorcentaje = variarEsteValor * (100.00 / 1023.00);
resultadoVoltios = variarEsteValor * (5.00 / 1023.00);
Console.Clear();
Console.WriteLine("Valor introducido: {0}", variarEsteValor);
Console.CursorVisible = false;
// Mostrar barra de porcentaje en pantalla.
Console.WriteLine();
Console.WriteLine("0 % 50 % 100 %");
Console.WriteLine("┌────────────────────────┬───────────────────────┐");
Console.ForegroundColor = ConsoleColor.Yellow;
// Se dibide por dos la barra del porcentaje para que quepa decuadamente en la pantalla.
mitadBarra = resultadoPorcentaje / 2;
if (mitadBarra > 50)
{
mitadBarra = 50;
}
for (int i = 1; i <= mitadBarra; i++)
{
Console.Write("█"); // Muestra ASCII 219 Dec y DB en Hex.
}
// Si sobre pasa 100, muestra # al final de la barra del porcentaje de color rojo.
if (resultadoPorcentaje > 100)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.Write("#");
}
Console.ForegroundColor = ConsoleColor.Gray; // Vuelve al color gris.
Console.WriteLine("\n");
Console.WriteLine("Percentage: " + resultadoPorcentaje.ToString("N2") + " %.");
Console.WriteLine("Voltage: " + resultadoVoltios.ToString("N2") + " V.");
Console.WriteLine("\n");
Console.Clear();
}
}
private static void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
Recibidos = sp.ReadLine();
//Console.WriteLine("Data Received:");
//Console.Clear(); // Limpiar pantalla.
Console.SetCursorPosition(5, 10); // Posición X, Y.
Console.Write(Recibidos);
}
}
}
Saludos.
Valora esta pregunta


0