简体   繁体   English

C# 从串口读取数据 - 如何只获取新/当前数据?

[英]C# Reading data from a serial port - How to only get new/current data?

I'm working on a project in ASP.NET and the code behind is in C#.我正在 ASP.NET 中开发一个项目,背后的代码是在 C# 中。 I've been reading data from a scale that sends me "YES" or "NOT" if the weight displayed on the scale is within two numbers that you set on the actual scale.如果秤上显示的重量在您在实际秤上设置的两个数字之内,我一直在从秤上读取数据,该秤会向我发送“是”或“否”。 As far as I know those two strings are the only data the scale can send.据我所知,这两个字符串是秤可以发送的唯一数据。 Right now, A button on the page reads data and changes a label to "good job" or "wrong" (Pretty simply just working on functionality right now).现在,页面上的一个按钮读取数据并将标签更改为“做得好”或“错误”(现在只是在处理功能)。 But I've been getting older data when I click the button, for example I'll click it twice with nothing on the scale and get "NOT" and the label will change to "wrong" but once I put something on the scale that is within the limit instead of getting "YES" I'll get something like "NOTYES".但是当我单击按钮时,我一直在获取旧数据,例如,我将在没有任何内容的情况下单击它两次并得到“NOT”并且标签将更改为“错误”但是一旦我在秤上放了一些东西在限制范围内,而不是得到“是”,我会得到类似“NOTYES”的东西。

I've got a ReadTimeout on the serial port and I have a thread, but I'm not to familiar with threads this is my first time doing something like this.我在串口上有一个 ReadTimeout 并且我有一个线程,但我不熟悉线程,这是我第一次做这样的事情。 I added a DiscardInBuffer() to the serial port and it seemed to help a bit, but not too much, I also wasn't too sure where to put it.我在串口上添加了一个 DiscardInBuffer() ,它似乎有点帮助,但不是太多,我也不太确定把它放在哪里。

I've also been printing to the console so I can see what data is actually getting read.我也一直在打印到控制台,所以我可以看到实际读取了哪些数据。 It constantly sends data so I'll have a huge string that is somewhat unpredictable like "NOT\\nNOT\\nNot\\n..." so that's why I cleaned the data.它不断发送数据,所以我会有一个有点不可预测的巨大字符串,比如“NOT\\nNOT\\nNot\\n...”,这就是我清理数据的原因。

The button has auto post back and the label is in an update panel, so it runs loadPage(), and then read() and then the buttonClick() - which is essentially useless at this point.该按钮具有自动回发功能,并且标签位于更新面板中,因此它运行 loadPage(),然后运行 ​​read(),然后运行 ​​buttonClick() - 这在这一点上基本上是无用的。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO.Ports;
using System.Diagnostics;
using System.Threading;

namespace ScaleTest
{

    public partial class WebForm1 : System.Web.UI.Page
    {
        public SerialPort port;
        public string scaleData = "";

        protected void Page_Load(object sender, EventArgs e)
        {

            if (IsPostBack)
            {
                Thread readThread = new Thread(Read);
                port = new SerialPort("COM3", 9600, Parity.None, 8, StopBits.One);
                port.ReadTimeout = 1000;
                if (port.IsOpen == false)
                    try
                    {
                        port.Open();
                    }
                    catch (Exception oex)
                    {
                        Debug.WriteLine(oex);
                    }
                readThread.Start();
                readThread.Join();
                port.Close();
            }
        }

        public void Read()
        {
            try
            {
                string message;
                string scaleData = port.ReadLine();
                port.DiscardInBuffer();
                Debug.WriteLine(scaleData);
                scaleData = scaleData.Trim().Replace("\r", string.Empty).Replace("\n", string.Empty);
                scaleData = String.Join("", scaleData.Distinct());


                Debug.WriteLine(scaleData);


                if (scaleData == "YES")
                {
                    message = "Good Job!";
                }
                else if (scaleData == "NOT")
                {
                    message = "WRONG!";
                }
                else
                {
                    message = "Try Again.";
                }
                ScaleLabel.Text = message;

            }
            catch (TimeoutException) { }
        }

        protected void ButtonClick(object sender, EventArgs e)
        {
        }

    }
}

If I start with nothing on the scale, run the program and press the button, scaleData will be "NOT" and the label will change to wrong which is correct.如果我从秤上没有任何内容开始,运行程序并按下按钮,scaleData 将是“NOT”,标签将更改为错误,这是正确的。 But if I put something on the scale within the limit and press the button again, I'll usually have to press the button a few times to get "YES" because it is getting old data and giving me stuff like "NOTYES".但是如果我在限制范围内在秤上放一些东西并再次按下按钮,我通常必须按下按钮几次才能得到“是”,因为它正在获取旧数据并给我诸如“NOTYS”之类的东西。

You can try this sample code in this link , which use ReadLine() Method您可以在此链接中尝试使用ReadLine()方法的示例代码

public static void Main()
{
     _serialPort = new SerialPort();
     _serialPort.BaudRate = 115200;
     _serialPort.PortName = "COM7";
     _serialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
}

private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
    try
    {
        SerialPort sp = (SerialPort)sender;
        if (!sp.IsOpen) return;

        string indata = _serialPort.ReadLine();
        Console.WriteLine(indata);
    }
    catch (Exception) {};
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM