Man*_*mar 5 c# serial-port winforms
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;
namespace WindowsFormsApp7
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
getavaialbleports();
}
void getavaialbleports()
{
String[] ports = SerialPort.GetPortNames();
comboBox1.Items.AddRange(ports);
}
private void button1_Click(object sender, EventArgs e)
{
try
{
if (comboBox1.Text == "" || comboBox2.Text == "")
{
textBox2.Text = "Please select port settings";
}
else
{
serialPort1.PortName = comboBox1.Text;
serialPort1.BaudRate = Convert.ToInt32(comboBox2.Text);
serialPort1.Open();
button1.Enabled = false;
}
}
catch(UnauthorizedAccessException)
{
textBox2.Text = "Unauthorised Access";
}
}
private void button2_Click(object sender, EventArgs e)
{
serialPort1.Close();
}
private void button3_Click(object sender, EventArgs e)
{
serialPort1.WriteLine(textBox1.Text);
textBox1.Text = "";
}
private void button4_Click(object sender, EventArgs e)
{
richTextBox1.Text = serialPort1.ReadLine();
}
}
}
Run Code Online (Sandbox Code Playgroud)
我可以从上面的代码发送数据,但对于接收,我无法从中读取数据。没有构建错误。请帮我解决这个问题。
您可以实现“SerialPortDataReceivedEvent”来从串口读取数据。在使用“DataReceivedEvent”打开与串行端口寄存器的连接之前,在button1_Click事件中添加以下代码。
serialPort1.DataReceived += new SerialDataReceivedEventHandler(mySerialPort_DataReceived);
Run Code Online (Sandbox Code Playgroud)
然后添加以下事件处理程序
private static void mySerialPort_DataReceived(
object sender,
SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string indata = sp.ReadExisting();
//data received on serial port is asssigned to "indata" string
//Console.WriteLine("Received data:");
//Console.Write(indata);
}
Run Code Online (Sandbox Code Playgroud)
另外,尝试配置其他属性,如奇偶校验、StopBits、DataBits 等,类似于另一端的设备(您尝试与之通信)。
更新 UI 上的数据:您需要的是一个委托方法,该方法使用Text给定的字符串设置文本框的属性。mySerialPort_DataReceived然后,您可以通过该方法从处理程序中调用该委托TextBox.Invoke()。像这样的东西:
public delegate void AddDataDelegate(String myString);
public AddDataDelegate myDelegate;
private void Form1_Load(object sender, EventArgs e)
{
//...
this.myDelegate = new AddDataDelegate(AddDataMethod);
}
public void AddDataMethod(String myString)
{
textbox1.AppendText(myString);
}
private void mySerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string indata = sp.ReadExisting();
textbox1.Invoke(this.myDelegate, new Object[] {indata});
}
Run Code Online (Sandbox Code Playgroud)
如果您需要进一步说明,请告诉我们。
希望这可以帮助..
| 归档时间: |
|
| 查看次数: |
16029 次 |
| 最近记录: |