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
Catch ex As ExceptionMessageBox.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();