Я новичок в COM PORT, хочу прочитать данные с весовой шкалы и отобразить в TextBox
.
Мне удалось получить данные, но они продолжают работать (потоковое).
Я хочу показать только если изменилось.
Мой код:
using System.Linq;
using System.IO.Ports;
public partial class Form1 : Form
{
private const int BaudRate = 9600;
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";
}
string str ="" ;
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;
str = System.Text.Encoding.UTF8.GetString(data);
textBox1.Text = str.ToString();
//_serialPort.Close();
//var newVal = _serialPort.ReadExisting();
//if (String.Compare(textBox1.Text, newVal) != 0.0)
// textBox1.Text = newVal;
}
}
private void button2_Click(object sender, EventArgs e)
{
//_serialPort.Close();
MessageBox.Show(str);
}
}