vb.net及C#串列埠基本通訊
vb.net
1.新增串列埠控制元件serialport
2.配置串列埠引數Public Sub Serial_Port_EFS1() '設定串列埠引數
With SerialPort_EFS1
.BaudRate = intEFS1_Baudrate
.PortName = strEFS1_COM '串列埠名稱
.DataBits = 8 '資料位
.StopBits = IO.Ports.StopBits.One '停止位
.Parity = IO.Ports.Parity.Odd '偶校驗
'.NewLine = vbCr & vbLf
.RtsEnable = True
End With
End Sub
3.串列埠接收
'觸發接收事件
Public Sub Sp_DataReceived_EFS(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort_EFS1.DataReceived
Me.Invoke(New EventHandler(AddressOf Sp_Receiving_EFS)) '呼叫接收資料函式
End Sub
'接收時間響應函式
'接收資料
(1)
Private Sub Sp_Receiving_EFS(ByVal sender As Object, ByVal e As EventArgs)
Dim StrInEFS As String = "", strCommand As String = "", strSendString As String = ""
Dim inDataLen, i As Integer
Dim strLen As UShort
Dim strHexSend As MatchCollection
Dim strList As New List(Of Byte)()
inDataLen = SerialPort_EFS1.BytesToRead() '讀取快取區位元組數
Try
If inDataLen > 0 Then
Dim inBytes_EFS(inDataLen - 1) As Byte
SerialPort_EFS1.Read(inBytes_EFS, 0, inDataLen)
SerialPort_EFS1.DiscardInBuffer()
end if
MessageBox.Show(ex.Message)
End Try
(2)
Dim inDataLen As Integer = SerialPort_MA.BytesToRead() '讀取快取區位元組數
If inDataLen > 0 Then
Dim inBytes_MA(inDataLen - 1) As Byte, bytes As Byte
SerialPort_MA.Read(inBytes_MA, 0, inDataLen)
For Each bytes In inBytes_MA
StrInMA = StrInMA + [String].Format("{0:X2} ", bytes) '顯示Ascii
Next
end if
4.傳送
(1)
strHexSend = Regex.Matches(strSendString, "(?i)[\da-f]{2}")
strList = New List(Of Byte)()
For Each m As Match In strHexSend
strList.Add(Byte.Parse(m.Value,
System.Globalization.NumberStyles.HexNumber))
Next
SerialPort_EFS1.Write(strList.ToArray(), 0, strList.Count)
(2)
Dim aByte_MA(7) As Byte
For i = 0 To 7
aByte_MA(i) = "&H" & (Mid("01080000AA555E94", 2 * i + 1, 2))
Next
SerialPort_MA.Write(aByte_MA, 0, aByte_MA.Length)
Dim ports As String() = SerialPort.GetPortNames()
Array.Sort(ports)
ComboBox1.Items.Clear()
ComboBox1.Items.AddRange(ports)
C#
1.增加所有可用串列埠
string [] spname=System.IO.Ports.SerialPort.GetPortNames();
if (spname.Length > 0)
{
foreach (string spName in spname)
comboBoxEx1.Items.Add(spName);
}
2.初始化串列埠
int intBaudrate,intDataBits;
string strPort,strStopBits,strParity;
intBaudrate = int.Parse(comboBoxEx2.SelectedItem.ToString());
strPort = comboBoxEx1.SelectedItem.ToString();
strStopBits = comboBoxEx4.SelectedItem.ToString();
strParity = comboBoxEx5.SelectedItem.ToString();
intDataBits = Convert.ToInt32(comboBoxEx3.SelectedItem.ToString());
frm_main.serialPort1.BaudRate = intBaudrate;
frm_main.serialPort1.PortName = strPort;
frm_main.serialPort1.Parity = (Parity)Enum.Parse(typeof(Parity), strParity);
frm_main.serialPort1.StopBits = (StopBits)Enum.Parse(typeof(StopBits), strStopBits);
frm_main.serialPort1.DataBits = intDataBits;
try
{
frm_main.serialPort1.Open();
//關鍵 為 serialPort1繫結事件控制代碼
//frm_main.serialPort1.DataReceived += new
SerialDataReceivedEventHandler(frm_main.serialPort1_DataReceived);
}
catch (Exception ee)
{
Console.WriteLine(new Exception(ee.Message));
MessageBox.Show(ee.Message, "提示");
}
3.串列埠傳送
try
{
string strHex;
strHex = "fafafafafade";
int i;
if ((strHex.Length % 2) != 0)
strHex += " ";
byte[] btHex = new byte[strHex.Length/2];
for (i = 0; i < btHex.Length; i++)
{
btHex[i] = Convert.ToByte(strHex.Substring(i*2, 2),16);//byte.Parse
(strHex.Substring(i,2));
}
this.serialPort1.Write(btHex, 0, btHex.Length);
}
catch (Exception ee)
{
MessageBox.Show(ee.Message, "提示");
}
4.串列埠接收
//開啟串列埠接收
this.serialPort1.DataReceived += new SerialDataReceivedEventHandler(this.serialPort1_DataReceived);
private void serialPort1_DataReceived(object sender,
System.IO.Ports.SerialDataReceivedEventArgs e)
{
//關鍵 代理
myDelegate md = new myDelegate(SetText);
try
{
if (serialPort1.IsOpen == true)
{
int DataLength = serialPort1.BytesToRead;
byte[] readBuffer = new byte[DataLength];
serialPort1.Read(readBuffer, 0, DataLength);
serialPort1.DiscardInBuffer();
string readstr = byteToHexStr(readBuffer);
Invoke(md, readstr);
}
}
catch (Exception err)
{
//throw err;
MessageBox.Show(err.Message, "提示");
}
}
//位元組陣列轉16進位制字串
public static string byteToHexStr(byte[] bytes)
{
string returnStr = "";
if (bytes != null)
{
for (int i = 0; i < bytes.Length; i++)
{
returnStr += bytes[i].ToString("X2");
}
}
return returnStr;
}
5.關閉串列埠
//關閉串列埠
this.serialPort1.Close();