您的位置:首页 > 编程语言 > C#

【转】使用Visual C# 2010编写串口程序

2014-12-12 10:02 274 查看
转自:http://blog.sina.com.cn/s/blog_6e59283f0100nn0i.html

新建一个project -在Visual C#大类中选择Windows Forms Application,自己填写工程名称,如SerialPort_Test;

下面在窗口中添加控件:在All Windows Forms中找(可根据需要自行添加其他)

serialPort1

Timer1 Interval设为100ms

Labal1+ComboBox1 (设定串口号)Labal1-Text设为“名称” ComboBox1-Item Collection设置com1—com12可选

Labal2+ComboBox2 (设定波特率)Labal2-Text设为“波特率” ComboBox2-Item Collection设置2400 4800 9600 38400 115200可选

Labal3+ComboBox3 (设定串口号)Labal3-Text设为“校验” ComboBox3-Item Collection设置Odd Even None可选

Labal4用来提示串口开启状态(False关,True开)

Botton1打开或关断串口

TestBox1显示从串口采到的数据

Timer1添加代码:

label4.Text = serialPort1.IsOpen.ToString();//定是检测,Label4显示串口状态

if (serialPort1.IsOpen)//如果串口是打开的,三个ComboBox不能修改,Button显示close

{

comboBox1.Enabled = false;

comboBox2.Enabled = false;

comboBox3.Enabled = false;

button1.Text="Close";

}

else //否则,ComboBox内容可以修改,Button显示open

{

comboBox1.Enabled = true;

comboBox2.Enabled = true;

comboBox3.Enabled = true;

button1.Text="Open";

}

ComboBox1添加代码

serialPort1.PortName = comboBox1.Text;//检测的串口是comboBox1的内容,也就是用户选择的串口

comboBox2添加代码

serialPort1.BaudRate = Convert.ToInt16(comboBox2.Text);//串口波特率是comboBox2选择的值

//因为.Text的内容为字符串,设置波特率需要转换为16位整型,所以调用Convert.ToInt16函数

comboBox3添加代码

switch(comboBox3.Text)//确定校验形式

{

case "None":

serialPort1.Parity=System.IO.Ports.Parity.None;

break;

case "Even":

serialPort1.Parity=System.IO.Ports.Parity.Even;

break;

case "Odd":

serialPort1.Parity=System.IO.Ports.Parity.Odd;

break;

}

Button1添加代码

if (button1.Text == "Close")//按钮显示close,click Button触发事件,关闭串口

{

serialPort1.Close();

}

else if (button1.Text == "Open")//按钮显示open,click后触发串口打开

{

serialPort1.Open();

}

串口数据获取函数

private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)

{

while (serialPort1.BytesToRead > 0)//保证每次数据读净,防止溢出

{

textBox1.Text += serialPort1.ReadChar();//在textBox1中显示串口受灾的数据



}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: