【问题标题】:Handling buffer data obtained from rs232 port处理从 rs232 端口获取的缓冲区数据
【发布时间】:2011-07-28 10:21:05
【问题描述】:

我有一个项目,希望我使用 rs232 从秤读取数据。秤的输出格式为“L00000”。我的问题是秤连续发送数据,因为它的重量类似于“L00000,L00001,L00002,L00003,L00004”。我在这种情况下的兴趣是获取要存储在数据库中的最后一部分“L00004”。 这是我的代码:请帮助我改进它。谢谢

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

namespace WindowsFormsApplication5
 {
public partial class Form1 : Form
{
    private List<byte> PortBuffer = new List<byte>();
    SerialPort comPort = new SerialPort("COM3", 9600, Parity.None, 8, StopBits.One);
    public Form1()
    {
        InitializeComponent();

    }

    private void button1_Click(object sender, EventArgs e)
    {


        if (comPort.IsOpen)
        {
            comPort.DiscardOutBuffer();
            MessageBox.Show("Data cleared");
            comPort.Close();
        }

        if(!comPort.IsOpen)
        {
        comPort.Open();
        //sample of data as written by the scale. How can I get the last chunk only so that I format it for my needs
        comPort.Write("L00002 L00002 L00002");

        int bytes = comPort.BytesToRead;
        byte[] buffer = new byte[bytes];
        comPort.Read(buffer, 0, buffer.Length);

        comPort.DataReceived += new SerialDataReceivedEventHandler(data_received);

        comPort.Close();
       }
       }
    public void data_received(object sender,SerialDataReceivedEventArgs e)
    {
        MessageBox.Show("test" + comPort.ReadExisting().ToString());

    }

   }
 }

【问题讨论】:

    标签: c# buffer port buffering


    【解决方案1】:

    数据是如何分隔的,a是空格还是不分隔?

    如果它是 a ,就像问题中那样

    var data=comPort.ReadExisting().ToString();
    var result=data.Split(',').Last();
    

    【讨论】:

    • No ,因此我用 Split(' ') 中的空格替换了它,但它似乎不起作用。你认为我很好地捕获了我的缓冲区数据:code int bytes = comPort.BytesToRead;字节[]缓冲区=新字节[字节]; comPort.Read(buffer, 0, buffer.Length);
    • 是的,我认为您已经将数据读入缓冲区。删除第一个代码中的读取命令。
    • 删除这 3 行,然后发布您从消息框中得到的确切数据?
    • 非常感谢它的工作。我只是删除了 3 行并得到了预期的结果。即 LXXXXXX。它甚至在真正的规模下也能工作。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-02
    • 2016-07-04
    • 1970-01-01
    • 2014-08-29
    • 2021-11-29
    相关资源
    最近更新 更多