从称重秤连续接收数据

时间:2015-03-12 05:53:49

标签: c# .net visual-studio serial-port

我正在使用Visual Studio 2008(C#)中的Windows 6应用程序。我正在尝试从称重秤接收重量。我能够减轻体重,但是每当体重发生变化时,体重就不会发生变化。它在代码中不断显示相同的权重。

例如:在启动应用程序时,它会连续显示正确​​的重量(00000),然后我更改了秤上的物体(新的重量00020),但它仍显示应用程序中的前一个重量(00000)。 p>

我的代码如下:

public partial class Form1 : Form
{
    public string hex;
    public bool isSet = false;
    private SerialPort _serialPort;         //<-- declares a SerialPort Variable to be used throughout the form
    private const int BaudRate = 2400;      //<-- BaudRate Constant. 9600 seems to be the scale-units default value

    public Form1()
    {
        InitializeComponent();
        _serialPort = new SerialPort("COM5", BaudRate, Parity.None, 8, StopBits.One);       //<-- Creates new SerialPort using the name selected in the combobox
    }

    private delegate void Closure();
    private void SerialPortOnDataReceived(object sender, SerialDataReceivedEventArgs serialDataReceivedEventArgs)
    {           
        if (InvokeRequired)
        {   //<-- Makes sure the function is invoked to work properly in the UI-Thread

                BeginInvoke(new Closure(() => { SerialPortOnDataReceived(sender, serialDataReceivedEventArgs); }));     //<-- Function invokes itself

        }
        else
        {
            textBox1.Text = "";

            while (_serialPort.BytesToRead > 0) //<-- repeats until the In-Buffer is empty
            {                   
                    //MessageBox.Show("byte");
                hex += string.Format("{0:X2} ", _serialPort.ReadByte());                   

            }
            if (hex != "")
            {
                byte[] data = FromHex(hex.Trim());
                textBox1.Text = Encoding.ASCII.GetString(data, 0, data.Length).Trim();
                isSet = true;                    
            }
            else
            {
                textBox1.Text = "no";
            }
        }
    }

    public byte[] FromHex(string aHex)
    {
        aHex = aHex.Replace(" ", "");
        byte[] raw = new byte[aHex.Length / 2];
        for (int i = 0; i < raw.Length; i++)
        {
            raw[i] = Convert.ToByte(aHex.Substring(i * 2, 2), 16);
        }
        return raw;
    } 

    private void button1_Click(object sender, EventArgs e)
    {
        isSet = false;
        textBox1.Text = "";


        _serialPort.DataReceived += SerialPortOnDataReceived;       //<-- this event happens everytime when new data is received by the ComPort
        try
        {
            _serialPort.Open();     //<-- make the comport listen
        }
        catch (Exception ex2)
        {
            //MessageBox.Show(ex2.Message);
        }
        textBox1.Text = "Listening on " + _serialPort.PortName + "...\r\n";
    }
}

如果我的问题不明确,请与我们联系。

1 个答案:

答案 0 :(得分:2)

使用ReadExisting()代替ReadByte()解决了我的问题。