短信收发类SerialStream.cs的用例--SerialStreamReader.cs

本文介绍了一个使用C#实现的串口通信示例程序。该程序通过COM2端口发送命令,并读取返回的响应。它设置了波特率为9600,并配置了超时时间为20毫秒。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

using System;
using System.IO;
using System.Threading;

using LoMaN.IO;

namespace SerialStreamReader {

class App {

// The main serial stream
static SerialStream ss;

[STAThread]
static void Main(string[] args) {

// Create a serial port
ss = new SerialStream();
try {
ss.Open("COM2");
}
catch (Exception e) {
Console.WriteLine("Error: " + e.Message);
return;
}

// Set port settings
ss.SetPortSettings(9600);

// Set timeout so read ends after 20ms of silence after a response
ss.SetTimeouts(20, 0, 0, 0, 0);

// Create the StreamWriter used to send commands
StreamWriter sw = new StreamWriter(ss, System.Text.Encoding.ASCII);

// Create the Thread used to read responses
Thread responseReaderThread = new Thread(new ThreadStart(ReadResponseThread));
responseReaderThread.Start();

// Read all returned lines
for (;;) {
// Read command from console
string command = Console.ReadLine();

// Check for exit command
if (command.Trim().ToLower() == "exit") {
responseReaderThread.Abort();
break;
}

// Write command to modem
sw.WriteLine(command);
sw.Flush();
}
}

// Main loop for reading responses
static void ReadResponseThread() {
StreamReader sr = new StreamReader(ss, System.Text.Encoding.ASCII);
try {
for (;;) {
// Read response from modem
string response = sr.ReadLine();
Console.WriteLine("Response: " + response);
}
}
catch (ThreadAbortException) {
}
}
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值