c# 2.0 serial port communication

本文介绍了一个简单的串口通信实现案例,包括串口初始化、发送指令、接收数据等关键步骤,并提供了完整的C#代码示例。

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

usingSystem;
usingSystem.Collections.Generic;
usingSystem.Text;
usingSystem.IO.Ports;

namespaceConsoleApplication3
...{
classSerialPortTest
...{
publicstringMessageStr="";
publicboolIsMessageFlag=false;

SerialPortport1;

/**////<summary>
///function:initialserialport
///</summary>
///<paramname="PortName">portnumber</param>
///<paramname="BaudRate">portspeed</param>


publicvoidInitCOM(stringPortName,intBaudRate)
...{
port1
=newSerialPort(PortName,BaudRate);
port1.Handshake
=Handshake.RequestToSend;

port1.DataReceived
+=newSerialDataReceivedEventHandler(port1_DataReceived);
}

/**////<summary>
///function:dealwiththedatareceive
///</summary>
///<paramname="sender"></param>
///<paramname="e"></param>

privatevoidport1_DataReceived(objectsender,SerialDataReceivedEventArgse)
...{
StringBuildercurrentline
=newStringBuilder();
if(!IsMessageFlag)
...{
while(port1.BytesToRead>0)
...{
charch=(char)port1.ReadByte();
currentline.Append(ch);
}

MessageStr
=currentline.ToString();
IsMessageFlag
=true;
currentline
=newStringBuilder();
}

//thrownewException("Themethodoroperationisnotimplemented.");
}

/**////<summary>
///function:sendtheinstruction
///</summary>
///<paramname="CommandString"></param>

publicvoidSendCommand(stringCommandString)
...{
byte[]WriteBuffer=Encoding.ASCII.GetBytes(CommandString);
port1.Write(WriteBuffer,
0,WriteBuffer.Length);
}

/**////<summary>
///function:opentheclosedport
///</summary>

publicvoidOpenPort()
...{
port1.Open();
if(port1.IsOpen)
...{
Console.WriteLine(
"theportisopened!");
}

else
...{
Console.WriteLine(
"failuretoopentheport!");
}

}

/**////<summary>
///function:closetheopenedport
///</summary>

publicvoidClosePort()
...{
port1.Close();
if(port1.IsOpen)
...{
Console.WriteLine(
"theportisalreadyclosed!");
}

}


}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值