2024年2月21日发(作者:)
C#串口通信实例
界面
程序:
注:Parity/databits/stopbits选择需用户自行添加代码。
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public SerialPort serialPort;
public static string ByteToString(byte[] InBytes)
{
string StringOut = "";
foreach (byte InByte in InBytes)
{
//StringOut = StringOut + ("{0:X2} ", InByte); //Display for
Hex
StringOut = StringOut + (char)InByte; //Display for ASCII
}
return StringOut;
}
private void Form1_Load(object sender, EventArgs e)
{
d = false;
string[] ports = tNames();
(ports);
ge(ports);
edIndex = 0;
("9600");
("19200");
("38400");
("115200");
edIndex = 0;
}
private void PortOpen_Click(object sender, EventArgs e)
{
if ( == "Open")
{
serialPort = new SerialPort();
me = ;
te = ();
= ;
ts = 8;
ts = ;
if ()
{
();
}
try
{
();
}
catch (Exception Ex)
{
Text(ng());
}
if ()
{
Text("串ä?口¨²打䨰开a成¨¦功|!ê?n");
= "Close";
d = true;
d = true;
}
}
else
{
();
= "Open";
Text("串ä?口¨²关?闭À?!ê?n");
d = false;
d = false;
}
}
private void SendBt_Click(object sender, EventArgs e)
{
();
}
private void TimeReciev_Tick(object sender, EventArgs e)
{
int count = oRead;
byte[] recievedbuffer = new byte[count];
(recievedbuffer,0,count);
Text(ByteToString(recievedbuffer));
}
}
}


发布评论