一、会用到一个串口控件:
serialPort
1.串口写入数据
2.串口读取数据
读取数据要在窗体加载的时侯添加一个数据接收事件。
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 _20_串口助手
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
}
private void label1_Click(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
duanKou.SelectedIndex = 0;
boTeiLv.SelectedIndex = 4;
//表示已通过serialPort1对象接收了数据。
//数据接收事件
serialPort2.DataReceived += new SerialDataReceivedEventHandler(port_DataReeived);//必须手动添加事件处理
}
//为DataReeived提供数据
private void port_DataReeived(object sender, SerialDataReceivedEventArgs e)//串口接收数据
{
if (!rad3.Checked)//如果接收模式为字符模式
{
string str = serialPort2.ReadExisting();//
outMsg.Text = str;
}
else
{
byte data;
data = (byte)serialPort2.ReadByte();//此处需要强制类型转换,将int类型数据转换为byte类型
string str = Convert.ToString(data, 16).ToUpper();//转换为大写十六进制字符串
outMsg.AppendText("0x" + (str.Length == 1 ? "0" + str : str) + " ");//空位补"0"
}
}
//打开端口
private void openDuan_Click(object sender, EventArgs e)
{
try
{
serialPort1.PortName = duanKou.Text;//获取端口名
serialPort1.BaudRate = Convert.ToInt32(boTeiLv.Text, 10);//获取波特率,十进制数据转换
serialPort1.Open();//端口打开
// serialPort2.PortName = duanKou.Text;//获取端口名
serialPort2.BaudRate = Convert.ToInt32(boTeiLv.Text, 10);//获取波特率,十进制数据转换
serialPort2.Open();//
openDuan.Enabled = false;//打开端口按钮显示灰色不可用
closeDuan.Enabled = true;//关闭端口按钮显示为可用
}
catch
{
MessageBox.Show("端口错误,请检查");
}
}
//关闭端口
private void closeDuan_Click(object sender, EventArgs e)
{
try
{
serialPort1.Close();//关闭端口
serialPort2.Close();//关闭端口
openDuan.Enabled = true;
closeDuan.Enabled = false;
}
catch
{
MessageBox.Show("端口异常,请检查");
}
}
//发送数据
private void send_Click(object sender, EventArgs e)
{
byte[] data=new byte[1];//每次发送一个字节
if (serialPort1.IsOpen)//端口打开才执行下面的语句
{
if (inMsg.Text.Length!=0)//判断是否有输入内容
{
if (!rad1.Checked)//如果发送模式是字符模式
{
try
{
serialPort1.WriteLine(inMsg.Text);//将输入的内容通过端口写入。
}
catch
{
MessageBox.Show("端口异常,请检查");
serialPort1.Close();//关闭端口
duanKou.Enabled = true;//打开端口按钮改为可用。
closeDuan.Enabled = false;//关闭端口按钮改为不可用。
}
}
else
{
for(int i = 0; i < inMsg.Text.Length / 2; i++)
{
data[0]=Convert.ToByte(inMsg.Text.Substring(i*2,2),16);//将获取到的数值转换为16进制;
serialPort1.Write(data, 0, 1);//通过端口循环发送(如果输入的是OAOAB,则只发送OA,OB)
}
if (inMsg.Text.Length % 2 != 0)
{
data[0] =Convert.ToByte(inMsg.Text.Substring(Text.Length-1,1),16);//单独发送B
serialPort1.Write(data, 0, 1);//通过端口发送。
}
}
}
}
else
{
MessageBox.Show("端口未开启,请检查");
}
}
}
}