最近の探査ではPC、レコードのいくつかの重要な一部でシンプルな外観であることを
C#のシリアル通信は、主にSystem.IO.Portsクラスを使用して行われるが、それはまだ非常に便利です
、次のように究極の効果がされています。
次のことを忘れてはいけません
シリアル設定を記入
我々は注意し、GetPortNames法によりマシンのポートのリストを取得することができます:コンピュータのポートに接続された異なるデバイスは、必ずしも同じではありません
string[] sps = SerialPort.GetPortNames();
他の関連するシリアル設定
ボーリストの例を
string[] baud = { "300", "1200", "2400", "4800", "9600", "19200", "38400", "57600" };
comboBox2.Items.AddRange(baud); //添加波特率列表
シリアルポートを開きます。
実際には、キーは、それが現在のシリアル属性判断でオンになっているかどうかであります
private void Button1_Click(object sender, EventArgs e)
{
//trycatcj处理串口打开过程中的异常
try
{
//将可能产生异常的代码放置在try块中
//根据当前串口属性来判断是否打开
if (serialPort1.IsOpen)
{
//串口已经处于打开状态
serialPort1.Close(); //关闭串口
button1.Text = "打开串口";
button1.BackColor = Color.ForestGreen;
comboBox1.Enabled = true;
comboBox2.Enabled = true;
comboBox3.Enabled = true;
comboBox4.Enabled = true;
comboBox5.Enabled = true;
ReceptTb.Text = ""; //清空接收区
SendTb.Text = ""; //清空发送区
}
else
{
//串口已经处于关闭状态,则设置好串口属性后打开
comboBox1.Enabled = false;
comboBox2.Enabled = false;
comboBox3.Enabled = false;
comboBox4.Enabled = false;
comboBox5.Enabled = false;
serialPort1.PortName = comboBox1.Text;
serialPort1.BaudRate = Convert.ToInt32(comboBox2.Text);
serialPort1.DataBits = Convert.ToInt16(comboBox3.Text);
if (comboBox4.Text.Equals("None"))
serialPort1.Parity = System.IO.Ports.Parity.None;
else if (comboBox4.Text.Equals("Odd"))
serialPort1.Parity = System.IO.Ports.Parity.Odd;
else if (comboBox4.Text.Equals("Even"))
serialPort1.Parity = System.IO.Ports.Parity.Even;
else if (comboBox4.Text.Equals("Mark"))
serialPort1.Parity = System.IO.Ports.Parity.Mark;
else if (comboBox4.Text.Equals("Space"))
serialPort1.Parity = System.IO.Ports.Parity.Space;
if (comboBox5.Text.Equals("1"))
serialPort1.StopBits = System.IO.Ports.StopBits.One;
else if (comboBox5.Text.Equals("1.5"))
serialPort1.StopBits = System.IO.Ports.StopBits.OnePointFive;
else if (comboBox5.Text.Equals("2"))
serialPort1.StopBits = System.IO.Ports.StopBits.Two;
serialPort1.Open(); //打开串口
button1.Text = "关闭串口";
button1.BackColor = Color.Firebrick;
this.Activate();
}
}
catch (Exception ex)
{
//捕获可能发生的异常并进行处理
//捕获到异常,创建一个新的对象,之前的不可以再用
serialPort1 = new System.IO.Ports.SerialPort();
//刷新COM口选项
comboBox1.Items.Clear();
comboBox1.Items.AddRange(System.IO.Ports.SerialPort.GetPortNames());
//响铃并显示异常给用户
System.Media.SystemSounds.Beep.Play();
button1.Text = "打开串口";
button1.BackColor = Color.ForestGreen;
MessageBox.Show(ex.Message);
comboBox1.Enabled = true;
comboBox2.Enabled = true;
comboBox3.Enabled = true;
comboBox4.Enabled = true;
comboBox5.Enabled = true;
}
}
メッセージング
また、これは非常に特別なものではありません、あなただけのWriteメソッドを呼び出すことができます
private void SendBtn_Click(object sender, EventArgs e)
{
try
{
Console.WriteLine(serialPort1.IsOpen);
//首先判断串口是否开启
if (serialPort1.IsOpen)
{
//串口处于开启状态,将发送区文本发送
serialPort1.Write(SendTb.Text);
SendTb.Text = "";
}
}
catch (Exception ex)
{
//捕获到异常,创建一个新的对象,之前的不可以再用
serialPort1 = new System.IO.Ports.SerialPort();
//刷新COM口选项
comboBox1.Items.Clear();
comboBox1.Items.AddRange(System.IO.Ports.SerialPort.GetPortNames());
//响铃并显示异常给用户
System.Media.SystemSounds.Beep.Play();
button1.Text = "打开串口";
button1.BackColor = Color.ForestGreen;
MessageBox.Show(ex.Message);
comboBox1.Enabled = true;
comboBox2.Enabled = true;
comboBox3.Enabled = true;
comboBox4.Enabled = true;
comboBox5.Enabled = true;
}
}
実際には、いくつかの基本的な機能は、単にメソッドを呼び出す以上のハンドルの例外を除いて結合することができます。
メッセージを受信します
受信メッセージのことは困難であり、単純に言って、非常に柔軟なシンプルなだけで受信したメッセージは確かに非常に簡単な方法を持つことができます表示するために、多くを聞いていない場合は、少し難しいです
これは最も簡単な方法ですが、単に結果の文字が一緒にスプライスされているバッファリングされますが、複数のクラス伝わってくるデータは、我々が時間内に、そのそれぞれを分離する必要がある場合は、バッファゾーンとステッチからこれを取り出しますバッファ文字から削除は必ずしも完全なものではありませんので、一緒に彼らは、として有用ではありません
String str = serialPort1.ReadExisting();
したがって、私は検索エンジンに回し、この問題を解決することを学んだ、私たちは最初、特定の文字累積バッファゾーン内の文字、バッファゾーンとその他を取得し、それぞれが空に、特定の文字を抽出読む必要がありますバッファゾーンは、私は配列に文字のこの文字列を取得します、私は三つのパラメータがあり、この例を持っているXYZ
が、周波数が高すぎると、まだ追いつくために、つまり、処理速度を問題を解決することはできません
private void SerialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
try
{
//因为要访问UI资源,所以需要使用invoke方式同步ui
this.Invoke((EventHandler)(delegate
{
int byteNumber = serialPort1.BytesToRead;
Thread.Sleep(20);
//延时等待数据接收完毕。
while ((byteNumber < serialPort1.BytesToRead) && (serialPort1.BytesToRead < 77))
{
byteNumber = serialPort1.BytesToRead;
Thread.Sleep(20);
}
int n = serialPort1.BytesToRead; //记录下缓冲区的字节个数
//Console.WriteLine("n" + n);
byte[] buf = new byte[n]; //声明一个临时数组存储当前来的串口数据
serialPort1.Read(buf, 0, n); //读取缓冲数据到buf中,同时将这串数据从缓冲区移除
string str = System.Text.Encoding.Default.GetString(buf);
string[] strArray = str.Split(',');
int count = 0;
for (int i = 0; i < strArray.Length; i++)
{
if(count == 0)
{
textBox1.Text = strArray[i];
}else if(count == 1)
{
textBox2.Text = strArray[i];
}else if(count == 2)
{
textBox3.Text = strArray[i];
}
count++;
if(count == 3)
{
count = 0;
}
}
}
)
);
}
catch (Exception ex)
{
//响铃并显示异常给用户
System.Media.SystemSounds.Beep.Play();
MessageBox.Show(ex.Message);
}
}