首先,设置连个相连接的串口;com2与com5相连,,com3与com4相连接
然后设置串口助手(相当于测深仪)为com2
c#代码:
using System; using System.IO.Ports; class PortDataReceived { public static void Main() { SerialPort mySerialPort = new SerialPort("COM1"); mySerialPort.BaudRate = 9600; mySerialPort.Parity = Parity.None; mySerialPort.StopBits = StopBits.One; mySerialPort.DataBits = 8; mySerialPort.Handshake = Handshake.None; mySerialPort.RtsEnable = true; mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler); mySerialPort.Open(); Console.WriteLine("Press any key to continue..."); Console.WriteLine(); Console.ReadKey(); mySerialPort.Close(); } private static void DataReceivedHandler( object sender, SerialDataReceivedEventArgs e) { SerialPort sp = (SerialPort)sender; string indata = sp.ReadExisting(); Console.WriteLine("Data Received:"); Console.Write(indata); } }
c++代码:
#using <System.dll> using namespace System; using namespace System::IO::Ports; ref class PortDataReceived { public: static void Main() { SerialPort^ mySerialPort = gcnew SerialPort("COM1"); mySerialPort->BaudRate = 9600; mySerialPort->Parity = Parity::None; mySerialPort->StopBits = StopBits::One; mySerialPort->DataBits = 8; mySerialPort->Handshake = Handshake::None; mySerialPort->RtsEnable = true; mySerialPort->DataReceived += gcnew SerialDataReceivedEventHandler(DataReceivedHandler); mySerialPort->Open(); Console::WriteLine("Press any key to continue..."); Console::WriteLine(); Console::ReadKey(); mySerialPort->Close(); } private: static void DataReceivedHandler( Object^ sender, SerialDataReceivedEventArgs^ e) { SerialPort^ sp = (SerialPort^)sender; String^ indata = sp->ReadExisting(); Console::WriteLine("Data Received:"); Console::Write(indata); } }; int main() { PortDataReceived::Main(); }
VB代码:
Imports System Imports System.IO.Ports Class PortDataReceived Public Shared Sub Main() Dim mySerialPort As New SerialPort("COM1") mySerialPort.BaudRate = 9600 mySerialPort.Parity = Parity.None mySerialPort.StopBits = StopBits.One mySerialPort.DataBits = 8 mySerialPort.Handshake = Handshake.None mySerialPort.RtsEnable = True AddHandler mySerialPort.DataReceived, AddressOf DataReceivedHandler mySerialPort.Open() Console.WriteLine("Press any key to continue...") Console.WriteLine() Console.ReadKey() mySerialPort.Close() End Sub Private Shared Sub DataReceivedHandler( sender As Object, e As SerialDataReceivedEventArgs) Dim sp As SerialPort = CType(sender, SerialPort) Dim indata As String = sp.ReadExisting() Console.WriteLine("Data Received:") Console.Write(indata) End Sub End Class
此示例将添加 SerialDataReceivedEventHandler 到 DataReceived 读取 COM1 端口上接收的所有可用的数据。 请注意为了测试此代码需要将附加 COM1,会将数据发送到的硬件。
网址:https://msdn.microsoft.com/zh-cn/library/system.io.ports.serialport.datareceived.aspx?cs-save-lang=1&cs-lang=vb#code-snippet-2