【问题标题】:How to check and ignore message from serial port?如何检查和忽略来自串口的消息?
【发布时间】:2015-10-28 03:39:34
【问题描述】:

我想忽略所有来自串行端口的消息,除了唯一的。我将每条消息添加到 hashSet 并且当新消息到达时我检查此消息是否包含在 hashSet 中,如果此消息不包含我想打印他,现在我的程序认为到达的每条消息都是唯一的,我不明白为什么我的比较代码不起作用,也许有人可以帮助我。这是我的代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.Ports;

namespace mySniffer
{
    class Program
    {
        static void Main(string[] args)
        {
            HashSet<String> messages = new HashSet<String>();
            SerialPort comPort = new SerialPort();
            comPort.BaudRate = 115200;
            comPort.PortName = "COM4";
            comPort.Open();
            while (true)
            {
                string rx = comPort.ReadLine(); //reading com port
                messages.Add(rx); // Add new incoming message to hashSet
                if (!messages.Contains(rx))
                {

                    Console.WriteLine(rx); // write incoming message
                }
                else { 
                    Console.WriteLine(messages.Count); // check how many messages in hashSet
                }
            }
        }
    }
}

【问题讨论】:

  • 你能给我们一个传入字符串的样本吗?
  • 这里是示例:0x30x980x20x00x80x2100x640x0
  • 我无法像那样重现您的错误。
  • 尝试循环发送随机数到串口,我用arduino做这个测试

标签: c# filter serial-port contains


【解决方案1】:

问题出在代码逻辑上,messages.Add(rx); 应该移到 if 块中。

【讨论】:

    猜你喜欢
    • 2011-01-19
    • 2013-01-15
    • 1970-01-01
    • 1970-01-01
    • 2011-07-27
    • 2012-09-18
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    相关资源
    最近更新 更多