Skip to content

Instantly share code, notes, and snippets.

@calumroy
Last active August 29, 2015 14:05
Show Gist options
  • Save calumroy/f0c8739d73682a5d8ec6 to your computer and use it in GitHub Desktop.
Save calumroy/f0c8739d73682a5d8ec6 to your computer and use it in GitHub Desktop.
###C# Serial Reader

###C# Serial Reader Visual studio

###C# Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.IO.Ports;
using System.IO;

namespace SerialRW
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            var p = new SerialPortProgram();
            Application.Run();
        }
    }

    class SerialPortProgram
    {
        public SerialPortProgram()
        {
            
            port = new SerialPort("COM6", 9600, Parity.None, 8, StopBits.One);
            //string path = @".\CanBusLog";
            //tw = new StreamWriter(path, true);
            // Open the port for communications
            port.NewLine = "\r";
            port.DataReceived += new SerialDataReceivedEventHandler(dataReceived);
            port.Open();

            Console.WriteLine("Incoming Data:");
            

        }

        void dataReceived(object sender, SerialDataReceivedEventArgs a)
        {
            //tw.WriteLine(port.ReadLine() + "\n");
            //tw.Close(); 
            string oldData = "";
            string newData = port.ReadLine();
            while (oldData != newData)
            {
                oldData = newData;
                logger.Trace(string.Format(
                    "{0}, {1}", DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss.ffffff"), newData));
                newData = port.ReadLine();
            }
            //logger.Trace(string.Format(
            //    "{0}, {1}", DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss.ffffff"), port.ReadLine()));
            //Console.WriteLine(port.ReadLine());
        }
        SerialPort port;
        NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger();
        private Queue<byte> recievedData = new Queue<byte>();

        //TextWriter tw;
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment