在C#中,可以使用以下方法進行串口通信:
using System;
using System.IO.Ports;
class Program
{
static void Main(string[] args)
{
SerialPort serialPort = new SerialPort("COM1", 9600); // 創建串口對象
serialPort.Open(); // 打開串口
// 讀取串口數據
string data = serialPort.ReadLine();
Console.WriteLine(data);
// 向串口發送數據
serialPort.WriteLine("Hello, World!");
// 關閉串口
serialPort.Close();
Console.ReadLine();
}
}
using System;
using System.Runtime.InteropServices;
class Program
{
[DllImport("kernel32.dll", SetLastError = true)]
static extern IntPtr CreateFile(string lpFileName, uint dwDesiredAccess, uint dwShareMode, IntPtr lpSecurityAttributes, uint dwCreationDisposition, uint dwFlagsAndAttributes, IntPtr hTemplateFile);
[DllImport("kernel32.dll")]
static extern bool ReadFile(IntPtr hFile, byte[] lpBuffer, uint nNumberOfBytesToRead, out uint lpNumberOfBytesRead, IntPtr lpOverlapped);
[DllImport("kernel32.dll")]
static extern bool WriteFile(IntPtr hFile, byte[] lpBuffer, uint nNumberOfBytesToWrite, out uint lpNumberOfBytesWritten, IntPtr lpOverlapped);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool CloseHandle(IntPtr hObject);
static void Main(string[] args)
{
IntPtr serialPort = CreateFile("COM1", 0x80000000, 0, IntPtr.Zero, 3, 0, IntPtr.Zero); // 打開串口
byte[] buffer = new byte[255];
uint bytesRead;
ReadFile(serialPort, buffer, (uint)buffer.Length, out bytesRead, IntPtr.Zero); // 讀取串口數據
Console.WriteLine(System.Text.Encoding.Default.GetString(buffer));
WriteFile(serialPort, System.Text.Encoding.Default.GetBytes("Hello, World!"), 13, out _, IntPtr.Zero); // 向串口發送數據
CloseHandle(serialPort); // 關閉串口
Console.ReadLine();
}
}
這些方法都可以用于實現串口通信,你可以根據自己的需求選擇其中一種適合的方法。