Ver Mensaje Individual
  #12 (permalink)  
Antiguo 04/01/2017, 09:03
REHome
 
Fecha de Ingreso: mayo-2007
Ubicación: PIC-16F84A
Mensajes: 727
Antigüedad: 17 años
Puntos: 8
Respuesta: Contar las tramas de byte recibidas

En otra manera. ;)

Código:
using System;
using System.IO;
using System.IO.Ports; // No olvidar.

namespace Puerto_Serie_Rread_consola
{
    class Program
    {
        static void Main(string[] args)
        {
            SerialPort mySerialPort = new SerialPort("COM4");

            mySerialPort.BaudRate = 115200;
            mySerialPort.Parity = Parity.None;
            mySerialPort.StopBits = StopBits.Two;
            mySerialPort.DataBits = 8;
            mySerialPort.Handshake = Handshake.None;
            mySerialPort.RtsEnable = true;

            mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);

            mySerialPort.Open();

            Console.WriteLine("Presione cualquier tecla para continuar...");
            Console.WriteLine();
            Console.ReadKey();
            mySerialPort.Close();
        }

        private static void DataReceivedHandler( object sender, SerialDataReceivedEventArgs e)
        {
            SerialPort sp = (SerialPort)sender;
            int count = 0;
            var datosArray = new byte[30000];
            while (count < datosArray.Length)
            {
                try
                {
                    count += sp.Read(datosArray, count, datosArray.Length - count);
                    Console.WriteLine("Dato recibido:");
                    Console.Write(count);
                }
                catch (TimeoutException)
                {
                    //maybe increase ReadTimeout or something, use exponential backoff, your call
                }
            }

            File.WriteAllBytes("fotón.jpg", datosArray); // Crear archivo en el disco duro.
            Console.WriteLine(datosArray.ToString());
        }
    }
}
Salida de la consola los últimos datos.
Cita:
28060Dato recibido:
28061Dato recibido:
28108Dato recibido:
28109Dato recibido:
28157Dato recibido:
28158Dato recibido:
28205Dato recibido:
28206Dato recibido:
28253Dato recibido:
28254Dato recibido:
28256
Acaba bien los 28256 como dato máximo. Si te fijas, se saltan números. Tiene que llegar de 0 al 28256. No se si es un fallo o algo raro.

A parte de esto, no me crea el archivo al final.
Código:
File.WriteAllBytes("fotón.jpg", datosArray); // Crear archivo en el disco duro.
__________________
Meta Shell, VERSIÓN 1.2.2
Descargar