串口軟件集成
1、串口初始化函數
初始化函數以按鍵點擊函數為起點。需要將各控件的參數幅值給串口各項參數,具體代碼如下:
private void button1_Click(object sender, EventArgs e)
{
// if(Button_on == 1)
if (!serialPort1.IsOpen)//如果串口是開
{
serialPort1.PortName = comboBox1.Text;
serialPort1.BaudRate = Convert.ToInt32(comboBox2.Text, 10);
float f = Convert.ToSingle(comboBox3.Text.Trim());
if (f == 0)//設置停止位
serialPort1.StopBits = StopBits.None;
else if (f == 1.5)
serialPort1.StopBits = StopBits.OnePointFive;
else if (f == 1)
serialPort1.StopBits = StopBits.One;
else if (f == 2)
serialPort1.StopBits = StopBits.Two;
else
serialPort1.StopBits = StopBits.One;
//設置數據位
serialPort1.DataBits = Convert.ToInt32(comboBox4.Text.Trim());
//設置奇偶校驗位
string s = comboBox5.Text.Trim();
if (s.CompareTo("無") == 0)
serialPort1.Parity = Parity.None;
else if (s.CompareTo("奇校驗") == 0)
serialPort1.Parity = Parity.Odd;
else if (s.CompareTo("偶校驗") == 0)
serialPort1.Parity = Parity.Even;
else
serialPort1.Parity = Parity.None;
try
{
serialPort1.Open(); //打開串口
button1.Text = "關閉串口";
comboBox1.Enabled = false;//關閉使能
comboBox2.Enabled = false;
comboBox3.Enabled = false;
comboBox4.Enabled = false;
comboBox5.Enabled = false;
}
catch
{
MessageBox.Show("串口打開失!");
}
}
else//如果串口是打開的則將其關閉
{
serialPort1.Close();
button1.Text = "打開串口";
comboBox1.Enabled = true;//使能配置
comboBox2.Enabled = true;
comboBox3.Enabled = true;
comboBox4.Enabled = true;
comboBox5.Enabled = true;
}
}
2、串口寫函數
寫函數主要用于發送數據,用到serialPort.write函數
本例以鼠標點擊按鍵觸發寫函數,代碼如下:
private void button_send_Click(object sender, EventArgs e)
{//發送數據
if(serialPort1.IsOpen)
{//如果串口開啟
if (textBox2.Text.Trim() != "")//如果框內不為空則
{
serialPort1.Write(textBox2.Text.Trim());//寫數據
}
else
{
MessageBox.Show("發送框沒有數據");
}
}
else
{
MessageBox.Show("串口未打開");
}
}
3、串口讀函數
串口讀函數主要用于讀取串口緩沖區的數據。
此處用到post_DataReceived事件
這里增減了兩種顯示方式:
1十六進制顯示 2字符串顯示
private void post_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
if (!radioButton1.Checked)
{
string str = serialPort1.ReadExisting();//字符串方式讀
textBox_receive.AppendText(str);
}
else
{
byte data;
data = (byte)serialPort1.ReadByte();
string str = Convert.ToString(data, 16).ToUpper();//
textBox_receive.AppendText("0x" + (str.Length == 1 ? "0" + str : str) + " ");
}
}