C # source code (original) of serial communication based on serial communication)

Source: Internet
Author: User

Mycom is a serial communication class and has complete code in the previous article of this blog. (C # Serial Communication Programming (modified ))
The following is the source code of the serial communication test program. The mycom class is stored in this project.
You can implement simple serial communication, and hope readers can have a preliminary understanding of the serial communication process through this program:

Using System;
Using System. Drawing;
Using System. Collections;
Using System. ComponentModel;
Using System. Windows. Forms;
Using System. Data;
Using System. Threading;
Namespace BusApp
{
/// <Summary>
/// Summary of Form1.
/// </Summary>
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; //,
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
/// <Summary>
/// Required designer variables.
/// </Summary>
Private System. ComponentModel. Container components = null;

Public Form1 ()
{
InitializeComponent ();
}

/// <Summary>
/// Clear all resources in use.
/// </Summary>
Protected override void Dispose (bool disposing)
{
If (disposing)
{
If (components! = Null)
{
Components. Dispose ();
}
}
Base. Dispose (disposing );
}

# Region code generated by Windows Form Designer
/// <Summary>
/// The designer supports the required methods-do not use the code editor to modify
/// Content of this method.
/// </Summary>
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 = "serial port number :";
//
// 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 = "set data packets :";
//
// 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 = "send ";
This. button1.Click + = new System. EventHandler (this. button#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 = "parameter settings ";
//
// 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 = "application settings ";
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 = "baud rate :";
//
// 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 = "Data bit :";
//
// 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 = "Stop bit :";
//
// 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 = "check bit :";
//
// 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 = "clear ";
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 = "initialization ";
//
// 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 = "set local address :";
//
// 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 = "Disable serial port ";
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 = "Serial Communication (small y design )";
This. Closing + = new System. ComponentModel. CancelEventHandler (this. Form1_Closing );
This. Load + = new System. EventHandler (this. form#load );
This. groupBox1.ResumeLayout (false );
This. ResumeLayout (false );

}
# Endregion

/// <Summary>
/// Main entry point of the application.
/// </Summary>
[STAThread]
Static void Main ()
{
Application. Run (new Form1 ());
}
// The program is enabled and the serial port is initialized.
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 ("Serial Port initialization successful ...... \ R \ n ");
Else
Msg. AppendText ("Serial Port initialization failed! \ R \ n ");
}
// Display package information
Public string dis_package (byte [] reb)
{
String temp = "";
Foreach (byte B in reb)
Temp + = B. ToString ("X2") + "";
Return temp;
}
// Enable serial port
Public bool OpenCom ()
{
Try
{
If (mycom1.Opened)
{
Mycom1.Close ();
Mycom1.Open (); // open the serial port
}
Else
{
Mycom1.Open (); // open the serial port
}
Return true;
}
Catch (Exception e)
{
MessageBox. Show ("error:" + e. Message );
Return false;
}

}
// Send button
Private void button#click (object sender, System. EventArgs e)
{
If (t_send.Text = "")
{MessageBox. Show ("sending data is blank! "); Return ;}
Byte [] temp1 = mysendb ();
Int sendnumb = 0;
Try
{
Sendnumb = mycom1.Write (temp1 );
Msg. AppendText ("\ r \ n send data (" + sendnumb + "):" + dis_package (temp1 ));
Recb = mycom1.Read (50 );
// If (recb. Length! = 0)
Msg. AppendText ("\ r \ n received data packet:" + dis_package (recb ));
}
Catch
{Msg. AppendText ("\ r \ n failed to send! "); Return ;}

// OpenCom ();
}
// Remove spaces from the sending Array
Public string delspace (string putin)
{
String putout = "";
For (int I = 0; I <putin. Length; I ++)
{
If (putin [I]! = '')
Putout + = putin [I];
}
Return putout;
}
// Extract data packets
Public byte [] mysendb ()
{
String temps = delspace (t_send.Text );
Byte [] tempb = new byte [50];
Int j = 0;
For (int I = 0; I <temps. Length; I = I + 2, j ++)
Tempb [j] = Convert. ToByte (temps. Substring (I, 2), 16 );
Byte [] send = new byte [j];
Array. Copy (tempb, send, j );
Return send;
}
// Clear button
Private void button3_Click (object sender, System. EventArgs e)
{
T_send.Text = string. Empty;
Msg. Text = string. Empty;
}

// Parameter settings
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); // values, 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 ("Serial Port initialization successful ...... \ R \ n ");
Else
Msg. AppendText ("Serial Port initialization failed! \ R \ n ");
}
// Close the program and end the serial port
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 = "enable serial port ";
Msg. AppendText ("\ r \ n serial port is disabled ...... ");
}
Else
{
Mycom1.Open ();
Button5.Text = "Disable serial port ";
Msg. AppendText ("\ r \ n serial port is successfully enabled ...... ");
}
}
}
}

Note: the format of the sent data packet is hexadecimal. For example, 02 45 66 FA can contain or has no space, but it must contain even digits.

TO everyone:

The program source code has been put in the first article of this blog to provide download.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.