从串行端口获取数据,并在DateTime C#中使用设置的时间



我正在使用Visual Studio 2015,并使用C#进行编码。

我已经在PIC32上编程了一个时钟,并通过串行端口发送了该时钟的数据。

我正在尝试从串行端口中放置一个字符串mydata并将其放入DateTime。但是我正在变得充满活力,不知道为什么。

我在mydata上得到的是这样:00:10:10:10:10:2300:10:10:10:10:10:10:10:2300:10:10:2300:10:10:23

你们能给我一个关注吗?

    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);
        }
    }
}

正如提到的@hans Passant,ReadExisting()仅返回接收缓冲区中当前的内容。DataReceived事件可以随机触发,因此,当此事件启动时,您可能还没有想要的所有字符。您需要构建一个字符串,直到拥有整个消息,然后可以显示文本。

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);
        }
    }
}

最新更新