C# 编写 自动识别串口是否被占用,不占用打开串口,读取串口指定字符串,把字符串写入excel保存,然后关闭串口等待30S重复上面操作
时间: 2023-12-10 15:02:36 浏览: 113
C#中串口接收数据并生成Excel和数据图片.zip_excel_excel 串口_excel串口_串口采集_采集
5星 · 资源好评率100%
以下是C#代码示例,可以实现你的需求:
```csharp
using System;
using System.IO.Ports;
using System.Threading;
using System.IO;
using Excel = Microsoft.Office.Interop.Excel;
namespace SerialPortReadWrite
{
class Program
{
static SerialPort _serialPort;
static Excel.Application _excelApp;
static void Main(string[] args)
{
_serialPort = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
while (true)
{
if (!_serialPort.IsOpen)
{
try
{
_serialPort.Open();
Console.WriteLine("串口已打开");
}
catch (Exception ex)
{
Console.WriteLine($"串口打开失败:{ex.Message}");
Thread.Sleep(30000);
continue;
}
}
bool isReadSuccessful = false;
string readString = string.Empty;
try
{
readString = _serialPort.ReadLine();
isReadSuccessful = true;
Console.WriteLine($"读取到的字符串:{readString}");
}
catch (TimeoutException)
{
Console.WriteLine("读取超时");
}
catch (Exception ex)
{
Console.WriteLine($"读取串口失败:{ex.Message}");
}
if (isReadSuccessful)
{
try
{
_excelApp = new Excel.Application();
Excel.Workbook workbook = _excelApp.Workbooks.Open("test.xlsx");
Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Worksheets[1];
worksheet.Cells[1, 1] = readString;
workbook.Save();
workbook.Close();
_excelApp.Quit();
Console.WriteLine("写入Excel成功");
}
catch (Exception ex)
{
Console.WriteLine($"写入Excel失败:{ex.Message}");
}
}
_serialPort.Close();
Console.WriteLine("串口已关闭");
Thread.Sleep(30000);
}
}
}
}
```
代码中使用了`SerialPort`类来操作串口,使用`Excel`类库来操作Excel文件,使用`Thread`类来实现等待30秒的功能。首先判断串口是否被占用,如果没有被占用则打开串口,然后读取串口数据并写入Excel文件,最后关闭串口并等待30秒后重复上述操作。需要注意的是,代码中的串口号和波特率需要根据具体的设备进行修改。
阅读全文