您的当前位置:首页正文

串口通信

2022-05-12 来源:意榕旅游网
VS2005使用SerialPort类设计串口通讯程序 2009-10-21 15:45 1. using System;

2. using System.IO.Ports; 3. using System.Threading; 4.

5. public class PortChat 6. {

7. static bool _continue;

8. static SerialPort _serialPort; 9.

10. public static void Main() 11. {

12. string name; 13. string message;

14. StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;

15. Thread readThread = new Thread(Read); 16.

17. // Create a new SerialPort object with default settings. 18.

19. _serialPort = new SerialPort(); 20.

21. // Allow the user to set the appropriate properties. 22.

23. _serialPort.PortName = SetPortName(_serialPort.PortName); 24. _serialPort.BaudRate = SetPortBaudRate(_serialPort.BaudRate); 25. _serialPort.Parity = SetPortParity(_serialPort.Parity);

26. _serialPort.DataBits = SetPortDataBits(_serialPort.DataBits); 27. _serialPort.StopBits = SetPortStopBits(_serialPort.StopBits); 28. _serialPort.Handshake =

SetPortHandshake(_serialPort.Handshake); 29.

30. // Set the read/write timeouts 31.

32. _serialPort.ReadTimeout = 500; 33. _serialPort.WriteTimeout = 500; 34.

35. _serialPort.Open(); 36. _continue = true; 37. readThread.Start(); 38.

39. Console.Write(\"Name: \"); 40. name = Console.ReadLine();

41.

42. Console.WriteLine(\"Type QUIT to exit\"); 43.

44. while (_continue) 45. {

46. message = Console.ReadLine(); 47.

48. if (stringComparer.Equals(\"quit\49. {

50. _continue = false; 51. } 52. else 53. {

54. _serialPort.WriteLine(

55. String.Format(\"<{0}>: {1}\56. } 57. } 58.

59. readThread.Join(); 60. _serialPort.Close(); 61. } 62.

63. public static void Read() 64. {

65. while (_continue) 66. { 67. try 68. {

69. string message = _serialPort.ReadLine(); 70. Console.WriteLine(message); 71. }

72. catch (TimeoutException) { } 73. } 74. } 75.

76. public static string SetPortName(string defaultPortName) 77. {

78. string portName; 79.

80. Console.WriteLine(\"Available Ports:\");

81. foreach (string s in SerialPort.GetPortNames()) 82. {

83. Console.WriteLine(\" {0}\84. }

85.

86. Console.Write(\"COM port({0}): \87. portName = Console.ReadLine(); 88.

89. if (portName == \"\") 90. {

91. portName = defaultPortName; 92. }

93. return portName; 94. } 95.

96. public static int SetPortBaudRate(int defaultPortBaudRate) 97. {

98. string baudRate; 99.

100. Console.Write(\"Baud Rate({0}): \101. baudRate = Console.ReadLine(); 102.

103. if (baudRate == \"\") 104. {

105. baudRate = defaultPortBaudRate.ToString(); 106. } 107.

108. return int.Parse(baudRate); 109. } 110.

111. public static Parity SetPortParity(Parity defaultPortParity) 112. {

113. string parity; 114.

115. Console.WriteLine(\"Available Parity options:\");

116. foreach (string s in Enum.GetNames(typeof(Parity))) 117. {

118. Console.WriteLine(\" {0}\119. } 120.

121. Console.Write(\"Parity({0}):\defaultPortParity.ToString());

122. parity = Console.ReadLine(); 123.

124. if (parity == \"\") 125. {

126. parity = defaultPortParity.ToString();

127. } 128.

129. return (Parity)Enum.Parse(typeof(Parity), parity); 130. } 131.

132. public static int SetPortDataBits(int defaultPortDataBits) 133. {

134. string dataBits; 135.

136. Console.Write(\"Data Bits({0}): \137. dataBits = Console.ReadLine(); 138.

139. if (dataBits == \"\") 140. {

141. dataBits = defaultPortDataBits.ToString(); 142. } 143.

144. return int.Parse(dataBits); 145. } 146.

147. public static StopBits SetPortStopBits(StopBits defaultPortStopBits) 148. {

149. string stopBits; 150.

151. Console.WriteLine(\"Available Stop Bits options:\"); 152. foreach (string s in Enum.GetNames(typeof(StopBits))) 153. {

154. Console.WriteLine(\" {0}\155. } 156.

157. Console.Write(\"Stop Bits({0}):\defaultPortStopBits.ToString());

158. stopBits = Console.ReadLine(); 159.

160. if (stopBits == \"\") 161. {

162. stopBits = defaultPortStopBits.ToString(); 163. } 164.

165. return (StopBits)Enum.Parse(typeof(StopBits), stopBits); 166. } 167.

168. public static Handshake SetPortHandshake(Handshake defaultPortHandshake) 169. {

170. string handshake; 171.

172. Console.WriteLine(\"Available Handshake options:\");

173. foreach (string s in Enum.GetNames(typeof(Handshake))) 174. {

175. Console.WriteLine(\" {0}\176. } 177.

178. Console.Write(\"Stop Bits({0}):\defaultPortHandshake.ToString());

179. handshake = Console.ReadLine(); 180.

181. if (handshake == \"\") 182. {

183. handshake = defaultPortHandshake.ToString(); 184. } 185.

186. return (Handshake)Enum.Parse(typeof(Handshake), handshake); 187. } 188. }

这个例子包括了这个控件几乎所有的操作,非常有参考价值.serialPort是在.net framework2.0中才有的东西,感觉这个东西和MSCOMM很相似。 使用SerialPort类设计串口通讯Windows Mobile 6下使用

程... serialPo... • 传感器(c#2.0)serialPort串口通...

最近读者:

C#:

1) 从工具箱选择SerialPort控件添加到窗体上,命名为SpCom 。 2) 设置通讯端口号及波特率、数据位、停止位和校验位。

SpCom.PortName = \"COM1\"; SpCom.BaudRate = 9600;

SpCom.Parity = IO.Ports.Parity.None;

SpCom.DataBits = 8;

SpCom.StopBits = IO.Ports.StopBits.One;

3) 发送数据

SpCom.Write(TextSendData.Text) ; 4) 添加接受事件

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

5) 读取数据

String strT;

strT=SpCom.ReadExisting();

C#实现串口通信源代码

默认分类 2009-09-17 14:56 阅读369 评论0

字号: 大 中 小

mycom是串口通信类,在本blog前一篇中有完整代码。( C#串口通信编程类(修改版) )

下面是串口通讯测试程序的源代码,将mycom类放在此项目中

可以实现简单的串口通信,希望读者能通过这个程序对串口通信过程有一个初步的了解:

using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms;

using System.Data; using System.Threading; namespace BusApp

{

///

/// Form1 的摘要说明。

///

public class Form1 : System.Windows.Forms.Form

{

private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Button button1; private System.Windows.Forms.GroupBox groupBox1;

private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label5; private System.Windows.Forms.Label label6; private System.Windows.Forms.Button button2; private System.Windows.Forms.Button button3; private System.Windows.Forms.Button button4; private System.Windows.Forms.TextBox textBox8; private System.Windows.Forms.Label label7;

public int iPort=1; //1,2,3,4

public int iRate=9600; //1200,2400,4800,9600

public byte bSize=8; //8 bits

public byte bParity=0; // 0-4=no,odd,even,mark,space

public byte bStopBits=1; // 0,1,2 = 1, 1.5, 2

public int iTimeout=1000;

public mycom mycom1=new mycom();

public byte[] recb;

private System.Windows.Forms.TextBox msg; private System.Windows.Forms.TextBox t_port; private System.Windows.Forms.TextBox t_rate; private System.Windows.Forms.TextBox t_bytesize; private System.Windows.Forms.TextBox t_stopbyte; private System.Windows.Forms.TextBox t_parity; private System.Windows.Forms.TextBox t_send;

private System.Windows.Forms.Button button5; //readTimeOut

///

/// 必需的设计器变量。

///

private System.ComponentModel.Container components = null;

public Form1()

{

InitializeComponent();

}

///

/// 清理所有正在使用的资源。

///

protected override void Dispose( bool disposing )

{

if( disposing )

{

if (components != null)

{

components.Dispose();

} }

base.Dispose( disposing );

}

#region Windows 窗体设计器生成的代码

///

/// 设计器支持所需的方法 - 不要使用代码编辑器修改

/// 此方法的内容。 ///

private void InitializeComponent()

{

this.msg = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.t_send = new System.Windows.Forms.TextBox(); this.button1 = new System.Windows.Forms.Button(); this.groupBox1 = new System.Windows.Forms.GroupBox();

this.button2 = new System.Windows.Forms.Button(); this.t_port = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label();

this.t_rate = new System.Windows.Forms.TextBox(); this.label4 = new System.Windows.Forms.Label(); this.t_bytesize = new System.Windows.Forms.TextBox();

this.label5 = new System.Windows.Forms.Label(); this.t_stopbyte = new System.Windows.Forms.TextBox();

this.label6 = new System.Windows.Forms.Label(); this.t_parity = new System.Windows.Forms.TextBox(); this.button3 = new System.Windows.Forms.Button(); this.button4 = new System.Windows.Forms.Button(); this.textBox8 = new System.Windows.Forms.TextBox(); this.label7 = new System.Windows.Forms.Label(); this.button5 = new System.Windows.Forms.Button();

this.groupBox1.SuspendLayout();

this.SuspendLayout();

// // msg //

this.msg.ForeColor = System.Drawing.Color.Green; this.msg.Location = new System.Drawing.Point(0, 0);

this.msg.Multiline = true; this.msg.Name = \"msg\";

this.msg.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;

this.msg.Size = new System.Drawing.Size(512, 264);

this.msg.TabIndex = 0;

this.msg.Text = \"\";

// // label1 //

this.label1.Location = new System.Drawing.Point(16, 24);

this.label1.Name = \"label1\";

this.label1.Size = new System.Drawing.Size(56, 16);

this.label1.TabIndex = 1; this.label1.Text = \"串口号:\";

// // label2 //

this.label2.ForeColor = System.Drawing.Color.FromArgb(((System.Byte)(192)), ((System.Byte)

(64)), ((System.Byte)(0)));

this.label2.Location = new System.Drawing.Point(8, 280);

this.label2.Name = \"label2\";

this.label2.Size = new System.Drawing.Size(80, 16);

this.label2.TabIndex = 1; this.label2.Text = \"设置数据包:\";

// // t_send //

this.t_send.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;

this.t_send.ForeColor = System.Drawing.Color.FromArgb(((System.Byte)(255)), ((System.Byte)

(128)), ((System.Byte)(0)));

this.t_send.Location = new System.Drawing.Point(80, 272);

this.t_send.Name = \"t_send\";

this.t_send.Size = new System.Drawing.Size(344, 21);

this.t_send.TabIndex = 2; this.t_send.Text = \"\";

// // button1

//

this.button1.Location = new System.Drawing.Point(432, 272);

this.button1.Name = \"button1\";

this.button1.Size = new System.Drawing.Size(40, 23);

this.button1.TabIndex = 3; this.button1.Text = \"发送\";

this.button1.Click += new System.EventHandler(this.button1_Click);

// // groupBox1

//

this.groupBox1.Controls.Add(this.button2); this.groupBox1.Controls.Add(this.t_port); this.groupBox1.Controls.Add(this.label1); this.groupBox1.Controls.Add(this.label3); this.groupBox1.Controls.Add(this.t_rate); this.groupBox1.Controls.Add(this.label4); this.groupBox1.Controls.Add(this.t_bytesize);

this.groupBox1.Controls.Add(this.label5); this.groupBox1.Controls.Add(this.t_stopbyte); this.groupBox1.Controls.Add(this.label6); this.groupBox1.Controls.Add(this.t_parity);

this.groupBox1.ForeColor = System.Drawing.Color.FromArgb(((System.Byte)(192)), ((System.

Byte)(64)), ((System.Byte)(0)));

this.groupBox1.Location = new System.Drawing.Point(8, 304);

this.groupBox1.Name = \"groupBox1\";

this.groupBox1.Size = new System.Drawing.Size(176, 216);

this.groupBox1.TabIndex = 4; this.groupBox1.TabStop = false; this.groupBox1.Text = \"参数设置\";

// // button2

//

this.button2.FlatStyle = System.Windows.Forms.FlatStyle.Popup; this.button2.Location = new System.Drawing.Point(80, 184);

this.button2.Name = \"button2\"; this.button2.TabIndex = 3; this.button2.Text = \"应用设置\";

this.button2.Click += new System.EventHandler(this.button2_Click);

// // t_port //

this.t_port.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;

this.t_port.Location = new System.Drawing.Point(80, 16);

this.t_port.Name = \"t_port\";

this.t_port.Size = new System.Drawing.Size(80, 21);

this.t_port.TabIndex = 2; this.t_port.Text = \"1\";

// // label3 //

this.label3.Location = new System.Drawing.Point(16, 58);

this.label3.Name = \"label3\";

this.label3.Size = new System.Drawing.Size(56, 16);

this.label3.TabIndex = 1; this.label3.Text = \"波特率:\";

// // t_rate //

this.t_rate.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;

this.t_rate.Location = new System.Drawing.Point(80, 50);

this.t_rate.Name = \"t_rate\";

this.t_rate.Size = new System.Drawing.Size(80, 21);

this.t_rate.TabIndex = 2; this.t_rate.Text = \"9600\";

//

// label4 //

this.label4.Location = new System.Drawing.Point(16, 92);

this.label4.Name = \"label4\";

this.label4.Size = new System.Drawing.Size(56, 16);

this.label4.TabIndex = 1; this.label4.Text = \"数据位:\";

// // t_bytesize

//

this.t_bytesize.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;

this.t_bytesize.Location = new System.Drawing.Point(80, 84);

this.t_bytesize.Name = \"t_bytesize\";

this.t_bytesize.Size = new System.Drawing.Size(80, 21);

this.t_bytesize.TabIndex = 2; this.t_bytesize.Text = \"8\";

// // label5 //

this.label5.Location = new System.Drawing.Point(16, 126);

this.label5.Name = \"label5\";

this.label5.Size = new System.Drawing.Size(56, 16);

this.label5.TabIndex = 1; this.label5.Text = \"停止位:\";

// // t_stopbyte

//

this.t_stopbyte.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;

this.t_stopbyte.Location = new System.Drawing.Point(80, 118);

this.t_stopbyte.Name = \"t_stopbyte\";

this.t_stopbyte.Size = new System.Drawing.Size(80, 21);

this.t_stopbyte.TabIndex = 2; this.t_stopbyte.Text = \"1\";

// // label6 //

this.label6.Location = new System.Drawing.Point(16, 160);

this.label6.Name = \"label6\";

this.label6.Size = new System.Drawing.Size(56, 16);

this.label6.TabIndex = 1; this.label6.Text = \"校验位:\";

// // t_parity

//

this.t_parity.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;

this.t_parity.Enabled = false;

this.t_parity.Location = new System.Drawing.Point(80, 152);

this.t_parity.Name = \"t_parity\";

this.t_parity.Size = new System.Drawing.Size(80, 21);

this.t_parity.TabIndex = 2; this.t_parity.Text = \"0\";

// // button3

//

this.button3.Location = new System.Drawing.Point(472, 272);

this.button3.Name = \"button3\";

this.button3.Size = new System.Drawing.Size(40, 23);

this.button3.TabIndex = 3; this.button3.Text = \"清空\";

this.button3.Click += new System.EventHandler(this.button3_Click);

// // button4

//

this.button4.FlatStyle = System.Windows.Forms.FlatStyle.Popup; this.button4.Location = new System.Drawing.Point(432, 312);

this.button4.Name = \"button4\";

this.button4.Size = new System.Drawing.Size(72, 23);

this.button4.TabIndex = 6; this.button4.Text = \"初始化\";

// // textBox8

//

this.textBox8.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;

this.textBox8.ForeColor = System.Drawing.Color.FromArgb(((System.Byte)(255)), ((System.By

te)(128)), ((System.Byte)(0)));

this.textBox8.Location = new System.Drawing.Point(288, 312);

this.textBox8.Name = \"textBox8\";

this.textBox8.Size = new System.Drawing.Size(136, 21);

this.textBox8.TabIndex = 7; this.textBox8.Text = \"\";

// // label7 //

this.label7.Location = new System.Drawing.Point(200, 320);

this.label7.Name = \"label7\";

this.label7.Size = new System.Drawing.Size(100, 16);

this.label7.TabIndex = 8; this.label7.Text = \"设置本机地址:\";

// // button5

//

this.button5.FlatStyle = System.Windows.Forms.FlatStyle.Popup; this.button5.Location = new System.Drawing.Point(440, 504);

this.button5.Name = \"button5\";

this.button5.Size = new System.Drawing.Size(64, 23);

this.button5.TabIndex = 9;

this.button5.Text = \"关闭串口\";

this.button5.Click += new System.EventHandler(this.button5_Click);

// // Form1 //

this.AutoScaleBaseSize = new System.Drawing.Size(6, 14); this.ClientSize = new System.Drawing.Size(512, 533);

this.Controls.Add(this.button5); this.Controls.Add(this.textBox8); this.Controls.Add(this.label7); this.Controls.Add(this.button4); this.Controls.Add(this.groupBox1); this.Controls.Add(this.button1); this.Controls.Add(this.t_send); this.Controls.Add(this.msg); this.Controls.Add(this.label2); this.Controls.Add(this.button3);

this.Name = \"Form1\";

this.Text = \"串口通讯(小y设计)\";

this.Closing += new System.ComponentModel.CancelEventHandler(this.Form1_Closing);

this.Load += new System.EventHandler(this.Form1_Load);

this.groupBox1.ResumeLayout(false);

this.ResumeLayout(false);

}

#endregion ///

/// 应用程序的主入口点。

///

[STAThread] static void Main()

{

Application.Run(new Form1());

}

//程序开启,串口初始化

private void Form1_Load(object sender, System.EventArgs e)

{

mycom1.PortNum=iPort; mycom1.BaudRate=iRate; mycom1.ByteSize=bSize; mycom1.Parity=bParity; mycom1.StopBits=bStopBits; mycom1.ReadTimeout=iTimeout;

if(this.OpenCom())

msg.AppendText(\"串口初始化成功……\\r\\n\");

else

msg.AppendText(\"串口初始化失败!\\r\\n\");

} //显示包信息

public string dis_package(byte[] reb)

{

string temp=\"\"; foreach(byte b in reb) temp+=b.ToString(\"X2\")+\" \";

return temp;

} //开串口

public bool OpenCom()

{ try {

if (mycom1.Opened)

{

mycom1.Close(); mycom1.Open(); //打开串口

} else {

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

} return true;

}

catch(Exception e)

{

MessageBox.Show(\"错误:\" + e.Message);

return false;

} } //发送按钮

private void button1_Click(object sender, System.EventArgs e)

{

if(t_send.Text==\"\")

{MessageBox.Show(\"发送数据为空!\");return;}

byte[] temp1=mysendb();

int sendnumb=0;

try {

sendnumb=mycom1.Write(temp1);

msg.AppendText(\"\\r\\n发送数据(\"+sendnumb+\"):\"+dis_package(temp1));

recb=mycom1.Read(50); //if(recb.Length!=0)

msg.AppendText(\"\\r\\n接收到数据包:\"+dis_package(recb));

} catch

{msg.AppendText(\"\\r\\n发送失败!\");return;}

//OpenCom();

}

//去掉发送数组中的空格 public string delspace(string putin)

{

string putout=\"\"; for(int i=0;i{ if(putin[i]!=' ') putout+=putin[i];

} return putout;

} //提取数据包 public byte[] mysendb()

{

string temps=delspace(t_send.Text);

byte[] tempb=new byte[50];

int j=0;

for(int i=0;itempb[j]=Convert.ToByte(temps.Substring(i,2),16);

byte[] send=new byte[j]; Array.Copy(tempb,send,j);

return send;

}

//清空按钮

private void button3_Click(object sender, System.EventArgs e)

{

t_send.Text=string.Empty; msg.Text=string.Empty;

} //参数设置

private void button2_Click(object sender, System.EventArgs e)

{

mycom1.PortNum=Convert.ToInt16(t_port.Text); //1,2,3,4

mycom1.BaudRate=Convert.ToInt16(t_rate.Text); //1200,2400,4800,9600

mycom1.ByteSize=Convert.ToByte(t_bytesize.Text,10); //8 bits

mycom1.Parity=Convert.ToByte(t_parity.Text,10); // 0-4=no,odd,even,mark,space mycom1.StopBits=Convert.ToByte(t_stopbyte.Text,10); // 0,1,2 = 1, 1.5, 2

//iTimeout=3; if(this.OpenCom())

msg.AppendText(\"串口初始化成功……\\r\\n\");

else

msg.AppendText(\"串口初始化失败!\\r\\n\");

}

//程序关闭,结束串口

private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e)

{

mycom1.Close();

}

private void button5_Click(object sender, System.EventArgs e)

{

if(mycom1.Opened)

{

mycom1.Close(); button5.Text=\"开启串口\";

msg.AppendText(\"\\r\\n串口被关闭……\");

} else {

mycom1.Open(); button5.Text=\"关闭串口\";

msg.AppendText(\"\\r\\n串口成功开启……\");

} } } }

mycom是串口通信类,在本blog前一篇中有完整代码。( C#串口通信编程类(修改版) ) 下面是串口通讯测试程序的源代码,将mycom类放在此项目中

可以实现简单的串口通信,希望读者能通过这个程序对串口通信过程有一个初步的了解:

using System;

using System.Drawing; using System.Collections; using System.ComponentModel;

using System.Windows.Forms; using System.Data; using System.Threading; namespace BusApp {

///

/// Form1 的摘要说明。 ///

public class Form1 : System.Windows.Forms.Form {

private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Button button1; private System.Windows.Forms.GroupBox groupBox1; private System.Windows.Forms.Label label3; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label5; private System.Windows.Forms.Label label6; private System.Windows.Forms.Button button2; private System.Windows.Forms.Button button3; private System.Windows.Forms.Button button4; private System.Windows.Forms.TextBox textBox8; private System.Windows.Forms.Label label7; public int iPort=1; //1,2,3,4

public int iRate=9600; //1200,2400,4800,9600 public byte bSize=8; //8 bits

public byte bParity=0; // 0-4=no,odd,even,mark,space public byte bStopBits=1; // 0,1,2 = 1, 1.5, 2 public int iTimeout=1000;

public mycom mycom1=new mycom(); public byte[] recb;

private System.Windows.Forms.TextBox msg; private System.Windows.Forms.TextBox t_port; private System.Windows.Forms.TextBox t_rate; private System.Windows.Forms.TextBox t_bytesize; private System.Windows.Forms.TextBox t_stopbyte; private System.Windows.Forms.TextBox t_parity;

private System.Windows.Forms.TextBox t_send;

private System.Windows.Forms.Button button5; //readTimeOut ///

/// 必需的设计器变量。 ///

private System.ComponentModel.Container components = null; public Form1() {

InitializeComponent(); }

///

/// 清理所有正在使用的资源。 ///

protected override void Dispose( bool disposing ) {

if( disposing ) {

if (components != null) {

components.Dispose(); } }

base.Dispose( disposing ); }

#region Windows 窗体设计器生成的代码 ///

/// 设计器支持所需的方法 - 不要使用代码编辑器修改 /// 此方法的内容。 ///

private void InitializeComponent() {

this.msg = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.t_send = new System.Windows.Forms.TextBox(); this.button1 = new System.Windows.Forms.Button(); this.groupBox1 = new System.Windows.Forms.GroupBox();

this.button2 = new System.Windows.Forms.Button(); this.t_port = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); this.t_rate = new System.Windows.Forms.TextBox(); this.label4 = new System.Windows.Forms.Label(); this.t_bytesize = new System.Windows.Forms.TextBox(); this.label5 = new System.Windows.Forms.Label(); this.t_stopbyte = new System.Windows.Forms.TextBox(); this.label6 = new System.Windows.Forms.Label(); this.t_parity = new System.Windows.Forms.TextBox(); this.button3 = new System.Windows.Forms.Button(); this.button4 = new System.Windows.Forms.Button(); this.textBox8 = new System.Windows.Forms.TextBox(); this.label7 = new System.Windows.Forms.Label(); this.button5 = new System.Windows.Forms.Button(); this.groupBox1.SuspendLayout(); this.SuspendLayout(); // // msg //

this.msg.ForeColor = System.Drawing.Color.Green; this.msg.Location = new System.Drawing.Point(0, 0); this.msg.Multiline = true; this.msg.Name = \"msg\";

this.msg.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.msg.Size = new System.Drawing.Size(512, 264); this.msg.TabIndex = 0; this.msg.Text = \"\"; // // label1 //

this.label1.Location = new System.Drawing.Point(16, 24); this.label1.Name = \"label1\";

this.label1.Size = new System.Drawing.Size(56, 16); this.label1.TabIndex = 1; this.label1.Text = \"串口号:\"; // // label2

//

this.label2.ForeColor = System.Drawing.Color.FromArgb(((System.Byte)(192)), ((System.Byte)(64)), ((System.Byte)(0)));

this.label2.Location = new System.Drawing.Point(8, 280); this.label2.Name = \"label2\";

this.label2.Size = new System.Drawing.Size(80, 16); this.label2.TabIndex = 1; this.label2.Text = \"设置数据包:\"; // // t_send //

this.t_send.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.t_send.ForeColor = System.Drawing.Color.FromArgb(((System.Byte)(255)), ((System.Byte)(128)), ((System.Byte)(0)));

this.t_send.Location = new System.Drawing.Point(80, 272); this.t_send.Name = \"t_send\";

this.t_send.Size = new System.Drawing.Size(344, 21); this.t_send.TabIndex = 2; this.t_send.Text = \"\"; // // button1 //

this.button1.Location = new System.Drawing.Point(432, 272); this.button1.Name = \"button1\";

this.button1.Size = new System.Drawing.Size(40, 23); this.button1.TabIndex = 3; this.button1.Text = \"发送\";

this.button1.Click += new System.EventHandler(this.button1_Click); //

// groupBox1 //

this.groupBox1.Controls.Add(this.button2); this.groupBox1.Controls.Add(this.t_port); this.groupBox1.Controls.Add(this.label1); this.groupBox1.Controls.Add(this.label3); this.groupBox1.Controls.Add(this.t_rate); this.groupBox1.Controls.Add(this.label4); this.groupBox1.Controls.Add(this.t_bytesize);

this.groupBox1.Controls.Add(this.label5); this.groupBox1.Controls.Add(this.t_stopbyte); this.groupBox1.Controls.Add(this.label6); this.groupBox1.Controls.Add(this.t_parity);

this.groupBox1.ForeColor = System.Drawing.Color.FromArgb(((System.Byte)(192)), ((System.Byte)(64)), ((System.Byte)(0)));

this.groupBox1.Location = new System.Drawing.Point(8, 304); this.groupBox1.Name = \"groupBox1\";

this.groupBox1.Size = new System.Drawing.Size(176, 216); this.groupBox1.TabIndex = 4; this.groupBox1.TabStop = false; this.groupBox1.Text = \"参数设置\"; // // button2 //

this.button2.FlatStyle = System.Windows.Forms.FlatStyle.Popup; this.button2.Location = new System.Drawing.Point(80, 184); this.button2.Name = \"button2\"; this.button2.TabIndex = 3; this.button2.Text = \"应用设置\";

this.button2.Click += new System.EventHandler(this.button2_Click); // // t_port //

this.t_port.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.t_port.Location = new System.Drawing.Point(80, 16); this.t_port.Name = \"t_port\";

this.t_port.Size = new System.Drawing.Size(80, 21); this.t_port.TabIndex = 2; this.t_port.Text = \"1\"; // // label3 //

this.label3.Location = new System.Drawing.Point(16, 58); this.label3.Name = \"label3\";

this.label3.Size = new System.Drawing.Size(56, 16); this.label3.TabIndex = 1; this.label3.Text = \"波特率:\";

// // t_rate //

this.t_rate.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.t_rate.Location = new System.Drawing.Point(80, 50); this.t_rate.Name = \"t_rate\";

this.t_rate.Size = new System.Drawing.Size(80, 21); this.t_rate.TabIndex = 2; this.t_rate.Text = \"9600\"; // // label4 //

this.label4.Location = new System.Drawing.Point(16, 92); this.label4.Name = \"label4\";

this.label4.Size = new System.Drawing.Size(56, 16); this.label4.TabIndex = 1; this.label4.Text = \"数据位:\"; //

// t_bytesize //

this.t_bytesize.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;

this.t_bytesize.Location = new System.Drawing.Point(80, 84); this.t_bytesize.Name = \"t_bytesize\";

this.t_bytesize.Size = new System.Drawing.Size(80, 21); this.t_bytesize.TabIndex = 2; this.t_bytesize.Text = \"8\"; // // label5 //

this.label5.Location = new System.Drawing.Point(16, 126); this.label5.Name = \"label5\";

this.label5.Size = new System.Drawing.Size(56, 16); this.label5.TabIndex = 1; this.label5.Text = \"停止位:\"; //

// t_stopbyte //

this.t_stopbyte.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;

this.t_stopbyte.Location = new System.Drawing.Point(80, 118); this.t_stopbyte.Name = \"t_stopbyte\";

this.t_stopbyte.Size = new System.Drawing.Size(80, 21); this.t_stopbyte.TabIndex = 2; this.t_stopbyte.Text = \"1\"; // // label6 //

this.label6.Location = new System.Drawing.Point(16, 160); this.label6.Name = \"label6\";

this.label6.Size = new System.Drawing.Size(56, 16); this.label6.TabIndex = 1; this.label6.Text = \"校验位:\"; // // t_parity //

this.t_parity.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.t_parity.Enabled = false;

this.t_parity.Location = new System.Drawing.Point(80, 152); this.t_parity.Name = \"t_parity\";

this.t_parity.Size = new System.Drawing.Size(80, 21); this.t_parity.TabIndex = 2; this.t_parity.Text = \"0\"; // // button3 //

this.button3.Location = new System.Drawing.Point(472, 272); this.button3.Name = \"button3\";

this.button3.Size = new System.Drawing.Size(40, 23); this.button3.TabIndex = 3; this.button3.Text = \"清空\";

this.button3.Click += new System.EventHandler(this.button3_Click); // // button4 //

this.button4.FlatStyle = System.Windows.Forms.FlatStyle.Popup;

this.button4.Location = new System.Drawing.Point(432, 312); this.button4.Name = \"button4\";

this.button4.Size = new System.Drawing.Size(72, 23); this.button4.TabIndex = 6; this.button4.Text = \"初始化\"; //

// textBox8 //

this.textBox8.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;

this.textBox8.ForeColor = System.Drawing.Color.FromArgb(((System.Byte)(255)), ((System.Byte)(128)), ((System.Byte)(0)));

this.textBox8.Location = new System.Drawing.Point(288, 312); this.textBox8.Name = \"textBox8\";

this.textBox8.Size = new System.Drawing.Size(136, 21); this.textBox8.TabIndex = 7; this.textBox8.Text = \"\"; // // label7 //

this.label7.Location = new System.Drawing.Point(200, 320); this.label7.Name = \"label7\";

this.label7.Size = new System.Drawing.Size(100, 16); this.label7.TabIndex = 8;

this.label7.Text = \"设置本机地址:\"; // // button5 //

this.button5.FlatStyle = System.Windows.Forms.FlatStyle.Popup; this.button5.Location = new System.Drawing.Point(440, 504); this.button5.Name = \"button5\";

this.button5.Size = new System.Drawing.Size(64, 23); this.button5.TabIndex = 9; this.button5.Text = \"关闭串口\";

this.button5.Click += new System.EventHandler(this.button5_Click); // // Form1 //

this.AutoScaleBaseSize = new System.Drawing.Size(6, 14); this.ClientSize = new System.Drawing.Size(512, 533); this.Controls.Add(this.button5); this.Controls.Add(this.textBox8); this.Controls.Add(this.label7); this.Controls.Add(this.button4); this.Controls.Add(this.groupBox1); this.Controls.Add(this.button1); this.Controls.Add(this.t_send); this.Controls.Add(this.msg); this.Controls.Add(this.label2); this.Controls.Add(this.button3); this.Name = \"Form1\";

this.Text = \"串口通讯(小y设计)\";

this.Closing += new System.ComponentModel.CancelEventHandler(this.Form1_Closing);

this.Load += new System.EventHandler(this.Form1_Load); this.groupBox1.ResumeLayout(false); this.ResumeLayout(false); }

#endregion ///

/// 应用程序的主入口点。 /// [STAThread] static void Main() {

Application.Run(new Form1()); }

//程序开启,串口初始化

private void Form1_Load(object sender, System.EventArgs e) {

mycom1.PortNum=iPort; mycom1.BaudRate=iRate; mycom1.ByteSize=bSize; mycom1.Parity=bParity; mycom1.StopBits=bStopBits;

mycom1.ReadTimeout=iTimeout; if(this.OpenCom())

msg.AppendText(\"串口初始化成功……\\r\\n\"); else

msg.AppendText(\"串口初始化失败!\\r\\n\"); }

//显示包信息

public string dis_package(byte[] reb) {

string temp=\"\"; foreach(byte b in reb) temp+=b.ToString(\"X2\")+\" \"; return temp; } //开串口

public bool OpenCom() { try {

if (mycom1.Opened) {

mycom1.Close();

mycom1.Open(); //打开串口 } else {

mycom1.Open();//打开串口 }

return true; }

catch(Exception e) {

MessageBox.Show(\"错误:\" + e.Message); return false; } } //发送按钮

private void button1_Click(object sender, System.EventArgs e)

{

if(t_send.Text==\"\")

{MessageBox.Show(\"发送数据为空!\");return;} byte[] temp1=mysendb(); int sendnumb=0; try {

sendnumb=mycom1.Write(temp1);

msg.AppendText(\"\\r\\n发送数据(\"+sendnumb+\"):\"+dis_package(temp1)); recb=mycom1.Read(50); //if(recb.Length!=0)

msg.AppendText(\"\\r\\n接收到数据包:\"+dis_package(recb)); } catch

{msg.AppendText(\"\\r\\n发送失败!\");return;}

//OpenCom(); }

//去掉发送数组中的空格

public string delspace(string putin) {

string putout=\"\";

for(int i=0;iif(putin[i]!=' ') putout+=putin[i]; }

return putout; }

//提取数据包

public byte[] mysendb() {

string temps=delspace(t_send.Text); byte[] tempb=new byte[50]; int j=0;

for(int i=0;itempb[j]=Convert.ToByte(temps.Substring(i,2),16); byte[] send=new byte[j];

Array.Copy(tempb,send,j); return send; } //清空按钮

private void button3_Click(object sender, System.EventArgs e) {

t_send.Text=string.Empty; msg.Text=string.Empty; } //参数设置

private void button2_Click(object sender, System.EventArgs e) {

mycom1.PortNum=Convert.ToInt16(t_port.Text); //1,2,3,4

mycom1.BaudRate=Convert.ToInt16(t_rate.Text); //1200,2400,4800,9600 mycom1.ByteSize=Convert.ToByte(t_bytesize.Text,10); //8 bits

mycom1.Parity=Convert.ToByte(t_parity.Text,10); // 0-4=no,odd,even,mark,space

mycom1.StopBits=Convert.ToByte(t_stopbyte.Text,10); // 0,1,2 = 1, 1.5, 2

//iTimeout=3; if(this.OpenCom())

msg.AppendText(\"串口初始化成功……\\r\\n\"); else

msg.AppendText(\"串口初始化失败!\\r\\n\"); }

//程序关闭,结束串口

private void Form1_Closing(object sender, System.ComponentModel.CancelEventArgs e) {

mycom1.Close(); }

private void button5_Click(object sender, System.EventArgs e) {

if(mycom1.Opened) {

mycom1.Close(); button5.Text=\"开启串口\";

msg.AppendText(\"\\r\\n串口被关闭……\"); } else {

mycom1.Open(); button5.Text=\"关闭串口\";

msg.AppendText(\"\\r\\n串口成功开启……\"); } } } }

注意:发送数据包的格式是16进制数据如:02 45 66 FA 中间可以有或者没有空格,但要保证有偶数位

TO 大家:

该程序源码已经放到本blog第一篇提供下载。

---------------------------------------------------------------------

0 0

(请您对文章做出评价)

« 上一篇:怎么导出SQL所有用户表的字段信息 » 下一篇:VB下如何编写CRC校验程序

posted @ 2006-09-29 09:54 小y 阅读(29623) 评论(97) 编辑 收藏 网

摘 所属分类: [09] 串口通信&网络编程, [21] 我做的小程序

因篇幅问题不能全部显示,请点此查看更多更全内容