Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
428 views
in Technique[技术] by (71.8m points)

c# - How to display weight from weighing scale into a textbox via serial port RS-232 or usb converter?

I've been assigned to display weight from weighing scale (CAS CI-201A) into a textbox using C#. The weight will be sent via serial port RS-232 or USB converter. The scale is with me but I don't know where to start. How can I achieve my goal?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Have you tried anything yet?

If you want to use the serial port it makes sense to first give the user a way to select which port to use. This can be done easily, by filling a combobox with all available ports.

        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 code uses a form with a comboBox on it, called "comboBox1" (Default). You will need to add:

using System.IO.Ports;

to the using directives.

Then add a button (button1) and a multiline textbox (textbox1) to the form and add this code:

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

This also requires you to add:

    private SerialPort _serialPort;
    private const int BaudRate = 9600;

right below the opening brackets of

public partial class Form1 : Form

After clicking the button, all received data from the selected comPort will be displayed as hex values in the TextBox.

DISCLAIMER: The above code contains NO error-handling and will produce errors if button1 is clicked multiple times, due to the fact that the previous instance of "SerialPort" is not closed properly. Please remember this when using this example.

Regards Nico

Complete Code:

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...