1、引入using集
using System.IO.Ports;
2、定義全局變量
SerialPort serialPort = new SerialPort();
3、可以設置下拉列表(ComboBox)在窗體的Load事件中讀取電腦上的com口
foreach (string Serial_Name in SerialPort.GetPortNames())
{
comboBox1.Items.Add(Serial_Name);
}
4、在button按下時
if (!serialPort.IsOpen)
{
serialPort.PortName = comboBox1.SelectedItem.ToString();//串口名
serialPort.BaudRate = 19200; //波特率
serialPort.DataBits = 8; //標準數據位長度默認爲8
button1.Text = "關閉串口";
serialPort.Open(); //打開串口
}
else
{
button1.Text = "打開串口";
serialPort.Close();
}
5、轉換爲byte併發送命令
//命令轉換爲byte數組
private static byte[] GetPostData(string cmdStr)
{
byte[] array = new byte[cmdStr.Length / 2];
for(int i = 0; i < cmdStr.Length; i += 2)
{
array[i / 2] = Convert.ToByte(cmdStr.Substring(i, 2), 16);
}
return array;
}
private void button2_Click(object sender, EventArgs e)
{
if(serialPort.IsOpen)
{
serialPort.DiscardInBuffer();
byte[] array = GetPostData(發送的16進制命令);
serialPort.Write(array, 0, array.Length);//寫入命令
}
}
6、查看電腦com口:我的電腦右擊》管理》設備管理器》右邊有個端口(com),如果太多不知道哪個,拔下來重插哪個有變化就是那個