Get data from Serial Port and use set time in Datetime c#

783 views Asked by At

I am using Visual Studio 2015 and am coding using C#.

I've programmed a clock on my pic32 and sending the data of this clock over the serial port.

I'm trying trying to put a string mydata from the serial port and put it into Datetime. But i'm getting exeptions and don't know why.

What i'm getting on my myData is like this: 00:10:2300:10:2300:10:2300:10:2300:10:2300:10:2300:10:23

Could you guys give me a heads up on this?

    using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;
using System.Diagnostics;

namespace klokske
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            if (!mySerialPort.IsOpen)
            {
                mySerialPort.Open();
                rtRX.Text = "Port Opened";
            }
            else
                rtRX.Text = "Port busy";
        }

        DateTime dateTime;

        private void AnalogClock_Load(object sender, System.EventArgs e)
        {
            dateTime = DateTime.Parse(myData);
        }

              private string myData;
        private void mySerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
                myData = mySerialPort.ReadExisting();
                 this.Invoke(new EventHandler(displayText));
        }

        private void displayText(object o, EventArgs e)
        {
            rtRX.AppendText(myData);
        }
    }
}
1

There are 1 answers

0
Baddack On

As @Hans Passant mentioned, the ReadExisting() only returns what is currently in the receive buffer. The DataReceived event can fire randomly, so when this event is firing you may not have all the characters you are looking for yet. You need to build a string until you have the whole message then you can display the text.

char ESC = (char)27;
char CR = (char)13;
char LF = (char)10;
StringBuilder sb = new StringBuilder();

//in my case, the data im expected is ended with a Line Feed (LF)
//so I'll key on LF before I send my message
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
    string Data = serialPort1.ReadExisting();

    foreach (char c in Data)
    {
        if (c == LF)
        {
            sb.Append(c);

            this.Invoke(new EventHandler(sb.toString()));
        }
        else
        {
            //else, we append the char to our string that we are building
            sb.Append(c);
        }
    }
}