c# - 使用 C# 中的串行端口从地磅机获取重量

标签 c# .net wpf serial-port

我正在开发使用 C#.Net 从地磅机获取重量的应用程序。我尝试了很多方法,但是,没有从地磅机读取正确的数据格式重量。我得到像 ?x 这样的输出??????x?x?x??x???x??x???x???x? 连续从串口获取。我想从地磅机获取重量我的代码如下:

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;
using System.IO;

namespace SerialPortTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        String a = "";

        private void button1_Click(object sender, EventArgs e)
        {
        serialPort1 = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
         serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);

        if (serialPort1.IsOpen == false)
        {
            serialPort1.Open();
        }
        timer1.Start();
        button1.Enabled = false;
        button2.Enabled = true;
        }

        private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            a = a + serialPort1.ReadExisting();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (a.Length != 0)
            {
                textBox1.AppendText(a);
                a = "";
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (serialPort1.IsOpen == true)
            {
                serialPort1.Close();
                button2.Enabled = false;
                button1.Enabled = true;
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            if (serialPort1.IsOpen == true)
            {
                button1.Enabled = false;
                button2.Enabled = true;
            }
            else
            {
                button1.Enabled = true;
                button2.Enabled = false;
            }
        }
    }
}

我的代码是将串行端口数据中的文本附加到文本框,但是,它仅显示为 ?xxx?xxxx?xxxx?

任何人都可以帮助我如何使用 C# 从串口获取重量

感谢您阅读我的帖子!

最佳答案

您正在使用 ReadExisting(),该方法尝试将端口接收到的字节转换为字符串。如果转换失败,您会得到一个问号。默认编码是 ASCII,128 到 255 之间的字节值不是 ASCII 字符,因此会生成 ?

几个可能的原因,大致按可能性排列:

  • 使用了错误的波特率,尤其是猜测得太高。
  • 设备可能正在发送二进制数据,而不是字符串。这需要使用 Read() 而不是 ReadExisting 并解码二进制数据。
  • 屏蔽不够好的长电缆拾取电噪声。通过断开桥端的电缆即可轻松排除可能的原因。如果这停止了数据,那么它就不可能是噪音。

请务必仔细阅读手册。如果您没有或无法理解该设备,请联系该设备的供应商。

关于c# - 使用 C# 中的串行端口从地磅机获取重量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12278366/

相关文章:

wpf - 为什么不能使用DataTrigger设置TextBox.IsEnabled = True?

c# - MVVM WPF 中的数据绑定(bind)

c# - LINQ 不区分大小写

C# 网络服务

.net - 我应该对 View 模型上的方法或命令进行单元测试吗?

.net - 如何在 DataGrid 列标题上捕获 "Click"事件

c# - 为什么我的 Uninstall 方法没有从 msi 调用?

WPF自定义绘制多个进度条

c# - 枚举到 Int。整数到枚举。转换的最佳方式?

c# - 解析时出现 JSON 错误