C# 如何通过串口RS-232或USB转换器将称重秤的重量显示到文本框中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10614286/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to display weight from weighing scale into a textbox via serial port RS-232 or usb converter?
提问by user1398000
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?
我被分配使用 C# 将体重从秤 (CAS CI-201A) 显示到文本框中。重量将通过串口 RS-232 或 USB 转换器发送。规模与我同在,但我不知道从哪里开始。我怎样才能实现我的目标?
回答by Kh?i
Firstly, before you start to code anything, I would check whether you're using the right cable. Try open a serial terminal of your choice (HyperTerm, putty) and check whether there is any data at all.
首先,在您开始编写任何代码之前,我会检查您是否使用了正确的电缆。尝试打开您选择的串行终端(HyperTerm、putty)并检查是否有任何数据。
Be sure to configure the same baudrate, stopbits and parity on both the weight scale and your terminal program.
确保在体重秤和终端程序上配置相同的波特率、停止位和奇偶校验。
If you receive data (the terminal program should at least display some garbage), then you can move on to coding. If not, check if you're using the right cable (nullmodem aka crossed-over).
如果您收到数据(终端程序至少应该显示一些垃圾),那么您可以继续编码。如果没有,请检查您是否使用了正确的电缆(nullmodem aka crossed-over)。
When you're this far, then you may use the SerialPortclass of C#
http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.aspx
当你走到这一步时,你可以使用SerialPortC# http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.aspx的类
回答by Nicolas
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:
此代码使用一个带有组合框的表单,称为“comboBox1”(默认)。您需要添加:
using System.IO.Ports;
to the using directives.
到 using 指令。
Then add a button (button1) and a multiline textbox (textbox1) to the form and add this code:
然后在表单中添加一个按钮(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());
}
}
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.
单击该按钮后,所有从所选 comPort 接收到的数据将在 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.
免责声明:上面的代码不包含错误处理,如果多次单击 button1 会产生错误,这是由于“SerialPort”的前一个实例没有正确关闭。使用这个例子时请记住这一点。
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 + "...\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
}
}
}
}
}
回答by Adam Casey
Based on this:
基于此:
Listening on 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
监听 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
Being the ASCII for this:
作为此的 ASCII:
0033 ID_00: 10.6 kg
0033 ID_00:10.6公斤
You can get the result by trimming the received string. Assuming your listener puts the bytes into an array byte[] serialReceived:
您可以通过修剪接收到的字符串来获得结果。假设您的侦听器将字节放入数组中byte[] serialReceived:
string reading = System.Text.Encoding.UTF8.GetString(serialReceived);
textBox1.Text = reading.Substring(13);
回答by Anto sujesh
based on adam suggestion i converted the output to human readable format ( from ASCII to UTF8 ) i puts the bytes into an array byte[]
根据亚当的建议,我将输出转换为人类可读的格式(从 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();
}
}
here is the full working 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 + "...\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();
}
}
}
if your are using A&D EK V Calibration Model : AND EK-610V. you have use BaudRate = 2400; and DataBits = 7
如果您使用的是 A&D EK V 校准型号:AND EK-610V。你已经使用了 BaudRate = 2400; 和数据位 = 7
Note : if you get output like this

you have to check the BaudRate,DataBits (refer your weighing machine manual ) or check your cable
您必须检查 BaudRate、DataBits(请参阅您的称重机手册)或检查您的电缆
回答by Minu Haris
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;
}
}
}
回答by Minu Haris
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;
}
}
}
回答by Sardar Agabejli
I was using Anto sujesh's Code, but I had the problem that some of the values I got from the scale were corrupted. I solved it by buffering the values in a cache file.
我正在使用 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;

