【问题标题】:Why do I get partly strange values from serial port in C#为什么我从 C# 中的串口得到部分奇怪的值
【发布时间】:2017-08-14 21:38:29
【问题描述】:

我正在开发一个处理秤数据的程序。秤通过 USB 串行端口连接。 我正在使用这个问题的代码:How to display weight from weighing scale into a textbox via serial port RS-232 or usb converter?。 所以最重要的部分是工作。我从秤上得到重量作为字符串。

我的问题是,当秤将重量值 (10/s) 发送到计算机时,我得到以下值,例如:

13,0g; 13,0克; 12,9克; ,8 克; 12,7克; 2,6克; 12,5克; 12,4克; ,3g; 2,2克; 12,1g;

您可以看到,某些值已损坏,有时第一个字符丢失,或者有时前 2 个字符... 当我尝试使用秤制造商的其他程序读取值时,它工作正常,所有值都是正确的。

那么问题出在哪里?

我尝试了不同的波特率和其他设置,但没有任何帮助。 希望有人可以帮助我。

这是我用来从链接页面读取串行端口数据的代码。

using System;
using System.IO.Ports;          //<-- necessary to use "SerialPort"
using System.Windows.Forms;

namespace ComPortTests
{
    public partial class Form1 : Form
    {
        private SerialPort _serialPort;         //<-- declares a SerialPort Variable to be used throughout the form
        private const int BaudRate = 9600;      //<-- BaudRate Constant. 9600 seems to be the scale-units default value
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            string[] portNames = SerialPort.GetPortNames();     //<-- Reads all available comPorts
            foreach (var portName in portNames)
            {
                comboBox1.Items.Add(portName);                  //<-- Adds Ports to combobox
            }
            comboBox1.SelectedIndex = 0;                        //<-- Selects first entry (convenience purposes)
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //<-- This block ensures that no exceptions happen
            if(_serialPort != null && _serialPort.IsOpen)
                _serialPort.Close();
            if (_serialPort != null)
                _serialPort.Dispose();
            //<-- End of Block

            _serialPort = new SerialPort(comboBox1.Text, BaudRate, Parity.None, 8, StopBits.One);       //<-- Creates new SerialPort using the name selected in the combobox
            _serialPort.DataReceived += SerialPortOnDataReceived;       //<-- this event happens everytime when new data is received by the ComPort
            _serialPort.Open();     //<-- make the comport listen
            textBox1.Text = "Listening on " + _serialPort.PortName + "...\r\n";
        }

        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
            {
                int dataLength = _serialPort.BytesToRead;
                byte[] data = new byte[dataLength];
                int nbrDataRead = _serialPort.Read(data, 0, dataLength);
                if (nbrDataRead == 0)
                    return;
                string str = System.Text.Encoding.UTF8.GetString(data);
                textBox1.Text = str.ToString();
            }
        }
}

【问题讨论】:

  • 您能描述一下您是如何从这段代码获得问题中以分号分隔的列表的吗?在“消息”开头丢失数据的一个可能原因是您在单次读取中读取了“下一条”消息的一些数据,但最终以某种方式丢弃了它。这会导致下一次读取丢失一些初始字符。
  • 这些值一个接一个地显示在文本框中...
  • "这会导致下一次读取丢失一些初始字符" 那么我必须做些什么来防止这种情况发生呢?使用停止位?平价?流量控制?
  • 您必须存储您现在丢弃的数据。在str 中查找分号并将其后的所有内容保存到下一次读取之前。
  • 什么换行符?这是第一次在这个问题的任何地方提到换行符。

标签: c# .net serial-port


【解决方案1】:

我只需要添加以下行来缓冲缓存文件中的值。

现在它工作正常!非常感谢

        File.AppendAllText("buffer1.txt", str);

        string strnew = File.ReadLines("buffer1.txt").Last();

        textBox5.Text = strnew;

【讨论】:

    猜你喜欢
    • 2014-08-12
    • 2018-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-27
    • 2013-11-16
    相关资源
    最近更新 更多