串口通讯代码

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

using System;

using System.Collections.Generic;

using ponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

using System.IO.Ports; //导入串口的命名空间

namespace _01_SerialPort

{

public partial class Form1 : Form

{

public delegate void showReceiveDelegate(string text); //当采用响应模式,应申明一个委托,实现不同线程的控件实验

SerialPort com = new SerialPort("COM2", 9600, Parity.None, 8, StopBits.One);//初始化构造函数

public Form1()

{

InitializeComponent();

}

///

///窗体加载

///

///

///

private void Form1_Load(object sender, EventArgs e)

{

cmbPort.SelectedIndex = 0;

cmbBaudRate.SelectedIndex = 0;

cmbDataBits.SelectedIndex = 0;

cmbStopBits.SelectedIndex = 0;

cmbParity.SelectedIndex = 0;

}

///

///串口打开与关闭

///

///

///

private void btnOpen_Click(object sender, EventArgs e)

{

if (btnOpen.Text == "打开串口")

{

try

{

if (!com.IsOpen)

{

com.PortName = cmbPort.Text;

com.BaudRate = int.Parse(cmbBaudRate.Text);

com.DataBits = int.Parse(cmbDataBits.Text);

switch (cmbStopBits.SelectedIndex) {

case 0:

com.StopBits = StopBits.One; break;

case 1:

com.StopBits = StopBits.Two; break;

case 2:

com.StopBits = StopBits.OnePointFive; break;

case 3:

com.StopBits = StopBits.None; break;

}

switch (cmbParity.SelectedIndex)

{

case 0: com.Parity = Parity.None; break;

case 1: com.Parity = Parity.Odd; break;

case 2: com.Parity = Parity.Even; break;

}

com.Open();//打开串口

}

btnOpen.Text = "关闭串口";

txtStatus.Text = "串口已打开!";

btnSend.Enabled = true;

if (rbAck.Checked)

btnReceive.Enabled = true; //应答模式,接收按钮有效}

catch

{ txtStatus.Text = "串口打开错误或串口不存在!"; } }

else//关闭串口

try

{

if (com.IsOpen)

com.Close(); //关闭串口

btnOpen.Text = "打开串口";

txtStatus.Text = "串口已关闭!";

btnSend.Enabled = false ;

if (rbAck.Checked)

btnReceive.Enabled = false; //应答模式,接收按钮有效}

catch

{ txtStatus.Text = "串口关闭错误或串口不存在!"; }

}

///

///串口发送数据

///

///

///

private void btnSend_Click(object sender, EventArgs e)

{

try

{

byte[] data = null;

if(chkSendHex.Checked)

data = getBytesFromString(txtSend.Text);

else

data = Encoding.Default.GetBytes(txtSend.Text);

com.Write(data, 0, data.Length);

}

catch (Exception err)

{ txtStatus.Text = err.ToString(); }

相关文档
最新文档