c# - 连续接收来自秤的数据

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

我正在 Visual Studio 2008 (C#) 中开发 Windows 6 应用程序。我正在尝试从体重秤接收重量。我能够接收重量,但每当体重秤上的重量发生变化时,它都不会收到更改后的重量。它在代码中连续显示相同的权重。

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

我的代码如下:

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";
    }
}

如果我的问题不清楚,请告诉我。

最佳答案

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

关于c# - 连续接收来自秤的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29002759/

相关文章:

c# - 打包 C# 类库 (DLL) 的推荐方法是什么?

c# - 具有不同属性类型的 AutoMapper 对象

.net - 如何探索 .NET 应用程序中的托管堆来识别可能的内存优化?

visual-studio - Windows .rc 文件的免费资源编辑器?

c# - 我如何找到所有设置属性的地方?

c# - 从文本框计数,asp.net

c# - ConfigurationManager Save() 想要创建一个 tmp 文件

c# - MemoryStream:为什么在readByte之后转换为byte

c# - 如何获取 SQL CLR 程序集中发生的异常的堆栈跟踪

c++ - 在 C++ 中使用自由二维指针矩阵时崩溃