如何通过串口RS-232或USB转换器将称重秤的重量显示到文本框中?

时间:2012-05-16 07:59:29

标签: c# usb serial-port

我被指派使用C#将称重秤(CAS CI-201A)的重量显示到文本框中。重量将通过串行端口RS-232或USB转换器发送。规模与我同在,但我不知道从哪里开始。我怎样才能实现目标?

8 个答案:

答案 0 :(得分:9)

你有没有尝试过任何东西?

如果您想使用串口,​​首先让用户选择使用哪个端口是有意义的。通过使用所有可用端口填充组合框,可以轻松完成此操作。

        private void Form1_Load(object sender, EventArgs e)
    {
        string[] portNames = SerialPort.GetPortNames();
        foreach (var portName in portNames)
        {
            comboBox1.Items.Add(portName);
        }
        comboBox1.SelectedIndex = 0;
    }

此代码使用带有comboBox的表单,称为“comboBox1”(默认)。 您需要添加:

using System.IO.Ports;

到using指令。

然后在表单中添加一个按钮(button1)和一个多行文本框(textbox1)并添加以下代码:

        private void button1_Click(object sender, EventArgs e)
    {
        _serialPort = new SerialPort(comboBox1.Text, BaudRate, Parity.None, 8, StopBits.One);
        _serialPort.DataReceived += SerialPortOnDataReceived;
        _serialPort.Open();
        textBox1.Text = "Listening on " + comboBox1.Text + "...";
    }

    private void SerialPortOnDataReceived(object sender, SerialDataReceivedEventArgs serialDataReceivedEventArgs)
    {
        while(_serialPort.BytesToRead >0)
        {
            textBox1.Text += string.Format("{0:X2} ", _serialPort.ReadByte());
        }
    }

这还需要您添加:

    private SerialPort _serialPort;
    private const int BaudRate = 9600;

位于

的左括号下方
public partial class Form1 : Form

单击按钮后,所选comPort的所有接收数据将在TextBox中显示为十六进制值。

免责声明:上述代码不包含错误处理,如果多次单击button1会产生错误,因为前一个“SerialPort”实例没有正确关闭。使用此示例时请记住这一点。

关心Nico

完整代码:

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
            {
                while (_serialPort.BytesToRead > 0) //<-- repeats until the In-Buffer is empty
                {
                    textBox1.Text += string.Format("{0:X2} ", _serialPort.ReadByte());
                        //<-- bytewise adds inbuffer to textbox
                }
            }
        }
    }
}

答案 1 :(得分:5)

首先,在你开始编码任何东西之前,我会检查你是否使用了正确的电缆。尝试打开您选择的串行终端(HyperTerm,putty)并检查是否有任何数据。

确保在体重秤和终端程序上配置相同的波特率,停止位和奇偶校验。

如果您收到数据(终端程序至少应显示一些垃圾),那么您可以继续编码。如果没有,请检查您是否使用了正确的电缆(nullmodem又称为交叉)。

如果你这么远,那么你可以使用SerialPort类的C# http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.aspx

答案 2 :(得分:4)

基于此:

  

聆听COM1 ... 30 30 33 33 20 49 44 5F 30 30 3A 20 20 20 31 30   2E 36 20 6B 67 20 0D 0A 0D 0A

成为ASCII:

  <00> 0033 ID_00:10.6公斤

您可以通过修剪收到的字符串来获得结果。假设您的侦听器将字节放入数组byte[] serialReceived

string reading = System.Text.Encoding.UTF8.GetString(serialReceived);
textBox1.Text = reading.Substring(13);

答案 3 :(得分:2)

我使用的是Anto sujesh的代码,但我遇到的问题是,我从规模中获得的某些值已损坏。我通过缓存缓存文件中的值来解决它。

        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 = Encoding.UTF8.GetString(data);

            //Buffers values in a file
            File.AppendAllText("buffer1", str);

            //Read from buffer and write into "strnew" String
            string strnew = File.ReadLines("buffer1").Last();

            //Shows actual true value coming from scale
            textBox5.Text = strnew;

答案 4 :(得分:1)

基于adam建议我将输出转换为人类可读格式(从ASCII到UTF8) 我将字节放入数组byte []

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();
            }
        }

这是完整的工作代码

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();
            }
        }
}

如果您使用的是A&amp; D EK V校准型号:AND EK-610V。你使用BaudRate = 2400;和DataBits = 7

注意:如果你得到这样的输出 enter image description here

您必须检查BaudRate,DataBits(参考您的称重机器手册)或检查您的电缆

答案 5 :(得分:0)

using System;

using System.IO;

using System.IO.Ports;

namespace comport

{
    public partial class Form1 : Form

    {
        public Form1()

        {

            InitializeComponent();
        }

        private SerialPort _serialPort = null;

        private void Form1_Load(object sender, EventArgs e)
        {
            AppConfiguration.sConfigType = "default";

            _serialPort = new SerialPort("COM1", 9600, Parity.None, 8);

            _serialPort.DataReceived += new SerialDataReceivedEventHandler(_serialPort_DataReceived);

            _serialPort.Open();

        }

        void _serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            string data = _serialPort.ReadExisting();

            textBox2.Text = data;
        }
    }

}

答案 6 :(得分:0)

我正在使用 yaohua xk3190-a9 体重计指示器连接到我的串行端口。在尝试了很多代码之后,下面的代码终于为我工作了。我将代码粘贴到此处,以便任何人使用同一设备时都可以获取帮助。

    private SerialPort _serialPort;
    private const int BaudRate = 2400;
    private void Form1_Load(object sender, EventArgs e)
    {
        string[] portNames = SerialPort.GetPortNames();
        foreach (var portName in portNames)
        {
            comboBox1.Items.Add(portName);
        }
        comboBox1.SelectedIndex = 0;
        //<-- 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, 7, 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
    
    }
    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
        {
            string data = _serialPort.ReadExisting();
            if (data != null)
            {
                if (data.ToString() != "")
                {
                    if (data.Length > 6)
                    {
                        var result = data.Substring(data.Length - 5);
                        textBox1.Text = result.ToString().TrimStart(new Char[] { '0' });
                    }
                }
            }
          
        }
    }

答案 7 :(得分:-1)

    using System;
    using System.IO.Ports;         
    using System.Windows.Forms;
    namespace ComPortTests
    {
        public partial class Form1 : Form
        {
            public Form1()
            {
                InitializeComponent();
            }
                private SerialPort _serialPort = null;
    private void Form1_Load(object sender, EventArgs e)
    {
     _serialPort = new SerialPort("COM1", 9600, Parity.None, 8);

     _serialPort.DataReceived += new SerialDataReceivedEventHandler(_serialPort_DataReceived);

     _serialPort.Open();
    }

    void _serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)

            {

                string data = _serialPort.ReadExisting();
                textBox2.Text = data;    
            }
    }
}