c语言rs232 串口通信(C简单串口通信232)

简单的界面

c语言rs232 串口通信(C简单串口通信232)(1)

波特率 校验位 停止位 数据位 及串口号 使用ComboBox控件,并更改它们的NAME属性:

baudrateCbx;

parityCbx;

stopBitsCbx;

dataBitsCbx;

portscbx;

检查串口 打开串口 发送 接收 为Button控件,更改NAME属性:

checkbtn;

Openbtn;

sentbtn;

receivedbtn;

c语言rs232 串口通信(C简单串口通信232)(2)

c语言rs232 串口通信(C简单串口通信232)(3)

代码部分:

using System.IO.Ports;//引用

SerialPort sp1 = new SerialPort();//实例化

检查串口:

private void checkbtn_Click(object sender, EventArgs e)

{

string[] strCom = SerialPort.GetPortNames();

if (strCom == null)

{

MessageBox.Show("本机没有串口!", "Error");

return;

}

foreach (string comExist in strCom)

{

portscbx.Items.Add(comExist);

portscbx.SelectedIndex = 0;

}

}

打开串口:

private void button1_Click(object sender, EventArgs e)

{

sp1.Open();

openbtn.Text = "关闭串口";

portscbx.Enabled = false;

baudrateCbx.Enabled = false;

parityCbx.Enabled = false;

stopBitsCbx.Enabled = false;

dataBitsCbx.Enabled = false;

myopen = true;

}

波特率:

private void botelucbx_SelectedIndexChanged(object sender, EventArgs e)

{

sp1.BaudRate = Convert.ToInt16(baudrateCbx.Text.Trim());

}

校验位:

private void jiaoyancbx_SelectedIndexChanged(object sender, EventArgs e)

{

string sjjy = parityCbx.Text.Trim();

switch (sjjy)

{

case "无":

sp1.Parity = Parity.None;

break;

case "奇校验":

sp1.Parity = Parity.Odd;

break;

case "偶校验":

sp1.Parity = Parity.Even;

break;

default:

sp1.Parity = Parity.None;

break;

}

}

停止位:

private void tingzhicbx_SelectedIndexChanged(object sender, EventArgs e)

{

int f = (int)Convert.ToSingle(stopBitsCbx.Text.Trim()) * 10;

switch (f)

{

case 0:

sp1.StopBits = StopBits.None;

break;

case 10:

sp1.StopBits = StopBits.One;

break;

case 15:

sp1.StopBits = StopBits.OnePointFive;

break;

case 20:

sp1.StopBits = StopBits.Two;

break;

default:

sp1.StopBits = StopBits.None;

break;

}

}

数据位:

private void shujucbx_SelectedIndexChanged(object sender, EventArgs e)

{

sp1.DataBits = Convert.ToInt16(dataBitsCbx.Text.Trim());

}

串口号:

private void comboBox5_SelectedIndexChanged(object sender, EventArgs e)

{

sp1.PortName = portscbx.Text.Trim();

}

发送:

private void sentbtn_Click(object sender, EventArgs e)

{

System.Text.UTF8Encoding utf8 = new System.Text.UTF8Encoding();

byte[] writeBytes = utf8.GetBytes(textBox1.Text);

sp1.Write(writeBytes, 0, writeBytes.Length);

}

接收:

private void received_Click(object sender, EventArgs e)

{

System.Threading.Thread.Sleep(100);

System.Text.UTF8Encoding uft8 = new System.Text.UTF8Encoding();

byte[] readByres = new byte[sp1.BytesToRead];

sp1.Read(readByres, 0, readByres.Length);

string recevid = uft8.GetString(readByres);

textBox2.Text = recevid;

}

,

免责声明:本文仅代表文章作者的个人观点,与本站无关。其原创性、真实性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容文字的真实性、完整性和原创性本站不作任何保证或承诺,请读者仅作参考,并自行核实相关内容。文章投诉邮箱:anhduc.ph@yahoo.com

    分享
    投诉
    首页