连接串口
首先可以在 工具箱中搜索serialport,将控件拖到你的Winfrom窗口。
界面设计
打开串口
csharp
private void Connect_Click(object sender, EventArgs e)
{
serialPort1.PortName = comboBox2.Text;//端口名
serialPort1.BaudRate = int.Parse(comboBox3.Text);//比特率
serialPort1.StopBits = StopBits.One;//停止位
switch (comboBox4.Text)//校验位
{
case "None":
serialPort1.Parity = Parity.None;
break;
case "Odd":
serialPort1.Parity = Parity.Odd;
break;
case "Even":
serialPort1.Parity = Parity.Even;
break;
case "Mark":
serialPort1.Parity = Parity.Mark;
break;
}
serialPort1.DataBits = int.Parse(comboBox5.Text);//数据位
try
{
serialPort1.Open();//打开串口
bool b = serialPort1.CtsHolding;//CTS状态
label8.Text = b ? "1" : "0";
if (checkBox2.CheckState == CheckState.Checked)//判断是否勾选RTS
{
serialPort1.RtsEnable = true;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
button3.Text=serialPort1.IsOpen ? "关闭串口" : "打开串口";
}
发送数据
liens为全局变量,可以直接在richTextBox里输入,然后再点发送。
通过文件发送
csharp
private void OpenFile_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.InitialDirectory = "d:\\";//设置默认打开路径
// 设置文件过滤选项
openFileDialog.Filter = "文本文件 (*.txt)|*.txt|所有文件 (*.*)|*.*";
// 设置标题
openFileDialog.Title = "选择文件";
// 显示对话框
DialogResult result = openFileDialog.ShowDialog();
// 确认用户没有取消操作
if (result == DialogResult.OK)
{
// 获取选中的文件路径
string filePath = openFileDialog.FileName;
comboBox1.Items.Add(filePath);
liens = File.ReadAllText(filePath);//读取文件
comboBox1.Text = filePath;
richTextBox1.Text=liens;
}
}
发送数据
csharp
private void Send_Click(object sender, EventArgs e)
{
serialPort1.WriteLine(liens);
}
接收数据
csharp
private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
int len = serialPort1.BytesToRead;//获取可以读取的字节数
byte[] buff = new byte[len];//创建缓存数据数组
serialPort1.Read(buff, 0, len);//把数据读取到buff数组
if (checkBox1.Checked)//是否勾选十六进制显示
{
richTextBox1.AppendText(BitConverter.ToString(buff).Replace('-', ' ') + '\n');//转成十六进制显示
}
else
{
richTextBox1.AppendText(Encoding.ASCII.GetString(data));//转成ASCII码显示
richTextBox1.AppendText("\n");
}
}