1
我有一個項目,我期望使用rs232從一個規模讀取數據。秤的輸出格式爲「L00000」。我的問題是秤如「L00000,L00001,L00002,L00003,L00004」一樣連續發送數據。我對這種情況的興趣是獲取存儲在數據庫中的最後一部分「L00004」。 這是我的代碼:請幫助我改進它。謝謝處理從rs232端口獲得的緩衝區數據
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());
}
}
}
沒有,所以我用空格代替它斯普利特(」「),但它似乎沒有工作。你認爲我很好地捕獲了我的緩衝區數據: 'code' int bytes = comPort.BytesToRead; byte [] buffer = new byte [bytes]; comPort.Read(buffer,0,buffer.Length); – KIUFELIX
是的,我認爲你已經將數據讀入緩衝區。刪除第一個代碼中的讀取命令。 –
刪除這3行,然後發佈消息框中的確切數據? –