我正在通过串口通信开发体重秤程序 但我这样做....例如:
当我的时候使用put项目
app获得重量,然后停止与规模通信首先获得重量设置
gridviewrowcolumn
然后在用户放置时自动进行行更改
关于规模通信的第二项开始和相同的程序。
这是我的代码:
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.Threading;
namespace serial
{
public partial class Form1 : Form
{
private SerialPort _serialPort; //<-- declares a SerialPort Variable to be used throughout the form
private const int BaudRate = 9600;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
#region Form Load
try
{
//getRawWeight();
string[] portNames = SerialPort.GetPortNames(); //<-- Reads all available comPorts
foreach (var portName in portNames)
{
comboBox1.Items.Add(portName); //<-- Adds Ports to combobox
}
comboBox1.SelectedIndex = 0;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
#endregion
}
private void button1_Click(object sender, EventArgs e)
{
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
{
string reading = "";
reading += string.Format("{0:X2} ", _serialPort.ReadByte());
//<-- bytewise adds inbuffer to textbox
//string reading = System.Text.Encoding.UTF8.GetString(_serialPort);
textBox1.Text = reading.Substring(13);
}
}
}
}
}
答案 0 :(得分:0)
我会打开一次串口,然后将其打开,直到你关闭程序。您是否已成功与规模沟通?此外,像scale这样的设备有自己的按钮,每次推送时都会通过串口发送数据。您的代码有什么问题?它写的是什么呢?