开发者

Handling buffer data obtained from rs232 port

开发者 https://www.devze.com 2023-03-23 07:07 出处:网络
I have a project in which I am expected to read data from a scale using rs232. The output from the scale is in the format \"L00000\".My problem is that the scale sends data continuously as it weighs l

I have a project in which I am expected to read data from a scale using rs232. The output from the scale is in the format "L00000".My problem is that the scale sends data continuously as it weighs like "L00000,L00001,L00002,L00003,L00004". My interest in this case is to obtain the last part "L00004" to be stored in the db. Here is my code: Kindly help me improve it. Thanks

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

    }

   }
 }


How is the data seperated, is the a space a , or no seperation?

If its a , like in the question then

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

精彩评论

暂无评论...
验证码 换一张
取 消