在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();
}
}
这些方法都可以用于实现串口通信,你可以根据自己的需求选择其中一种适合的方法。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: C#中垃圾回收是怎么工作的