Create a C # serial communication program,

Source: Internet
Author: User

Create a C # serial communication program,

Create a C # serial communication program on the. NET platform. NET 2.0 provides the serial communication function. Its namespace is System. IO. Ports. This new framework can not only access the serial port on the computer, but also communicate with the serial port device. We will use standard RS 232 C for inter-PC communication. It works in full duplex mode, and we do not intend to use any handshake or stream controller, but instead use a non-modem connection. How to Create a C # serial communication program? Let's start:

Create a namespace for the C # serial communication program

The SerialPort class is the most reusable in the System. IO. Ports namespace.

Create a SerialPort object for C # serial communication program

By creating a SerialPort object, we can control the whole process of serial communication in the program.

The method of the SerialPort class we will use:

ReadLine (): Read the value of a new row from the input buffer. If not, NULL is returned.

WriteLine (string): Write and output buffer

Open (): Open a new serial port connection

Close (): Close

  1. // Create a Serial Port object
  2. SerialPort sp =NewSerialPort ();

By default, the value of DataBits is 8, StopBits is 1, and the communication port is com1. You can reset these settings in the following attributes:

BaudRate: the baud rate of the serial port

StopBits: the number of Stop bits per byte

ReadTimeout: The stop time when the read operation is not completed. Unit: milliseconds

There are also many other public attributes. You can refer to MSDN on your own.

Create a C # serial port communication program

During data transmission, each byte of data is transmitted through a single cable. The package includes the start bit, data, and end value. Once

Start bit transfer, data will be transmitted later, which may be 5, 6, 7, or 8 digits. It depends on your settings. The same settings must be set for sending and receiving

The baud rate and number of data digits.

Create C # Cat-free mode for serial communication program

Cables without Modem mode are simply crossover transmission and receiving lines. Similarly, DTR & DSR and RTS & CTS also need to be crossed.

Here, we have three lines. Interconnect 2 and 3 (A 2-pin segment connects 3pin), and connect the 5pin at both ends.

Create C # example program of serial communication program

If you want to use the default Property, press the Save Status button. If you want to change the Property, press "Property ". After setting, you can communicate.

Code of the Main Window

  1. # Region Using directives
  2.  
  3. UsingSystem;
  4. UsingSystem. Collections. Generic;
  5. UsingSystem. ComponentModel;
  6. UsingSystem. Data;
  7. UsingSystem. Drawing;
  8. UsingSystem. Windows. Forms;
  9. UsingSystem. IO. Ports;
  10.  
  11. # Endregion
  12.  
  13. NamespaceSerialexpample
  14. {
  15. PartialClassForm1: Form
  16. {
  17. // Create instance of property page
  18. // Property page is used to set values for stop bits and
  19. // Baud rate
  20.  
  21. PropertyPage pp =NewPropertyPage ();
  22.  
  23. // Create an Serial Port object
  24. SerialPort sp =NewSerialPort ();
  25.  
  26. PublicForm1 ()
  27. {
  28. InitializeComponent ();
  29. }
  30.  
  31. Private VoidPropertyButton_Click (ObjectSender, EventArgs e)
  32. {
  33. // Show property dialog
  34. Pp. ShowDialog ();
  35.  
  36. PropertyButton. Hide ();
  37. }
  38.  
  39. Private VoidSendButton_Click (ObjectSender, EventArgs e)
  40. {
  41. Try 
  42. {
  43. // Write line to serial port
  44. Sp. WriteLine (textBox. Text );
  45. // Clear the text box
  46. TextBox. Text = "";
  47. }
  48. Catch(System. Exception ex)
  49. {
  50. BaudRatelLabel. Text = ex. Message;
  51. }
  52.  
  53. }
  54.  
  55. Private VoidReadButton_Click (
  56. ObjectSender, EventArgs e)
  57. {
  58. Try 
  59. {
  60. // Clear the text box
  61. TextBox. Text = "";
  62. // Read serial port and displayed the data in text box
  63. TextBox. Text = sp. ReadLine ();
  64. }
  65. Catch(System. Exception ex)
  66. {
  67. BaudRatelLabel. Text = ex. Message;
  68. }
  69. }
  70.  
  71. Private VoidForm1_Load (ObjectSender, EventArgs e)
  72. {
  73.  
  74. }
  75.  
  76. Private VoidForm1_FormClosing (
  77. ObjectSender, FormClosingEventArgs e)
  78. {
  79. MessageBox. Show ("Do u want to Close the App ");
  80. Sp. Close ();
  81. }
  82.  
  83. Private VoidStartCommButton_Click (
  84. ObjectSender, EventArgs e)
  85. {
  86. StartCommButton. Hide ();
  87. SendButton. Show ();
  88. ReadButton. Show ();
  89. TextBox. Show ();
  90. }
  91.  
  92. // When we want to save the status (value)
  93. Private VoidSaveStatusButton_Click_1 (
  94. ObjectSender, EventArgs e)
  95. {
  96. // Display values
  97. // If no property is set the default values
  98. If(Pp. bRate = "" & pp. sBits = "")
  99. {
  100. DataBitLabel. Text = "BaudRate =" +
  101. Sp. BaudRate. ToString ();
  102. ReadTimeOutLabel. Text = "StopBits =" +
  103. Sp. StopBits. ToString ();
  104. }
  105. Else 
  106. {
  107. DataBitLabel. Text = "BaudRate =" +
  108. Pp. bRate;
  109. ReadTimeOutLabel. Text = "StopBits =" + pp. sBits;
  110. } // Create a C # serial communication program
  111.  
  112. ParityLabel. Text = "DataBits =" +
  113. Sp. DataBits. ToString ();
  114. StopBitLabel. Text = "Parity =" +
  115. Sp. Parity. ToString ();
  116. ReadTimeOutLabel. Text = "ReadTimeout =" +
  117. Sp. ReadTimeout. ToString ();
  118.  
  119. If(PropertyButton. Visible =True)
  120. PropertyButton. Hide ();
  121. SaveStatusButton. Hide ();
  122. StartCommButton. Show ();
  123.  
  124. Try 
  125. {
  126. // Open serial port
  127. Sp. Open ();
  128. // Set read time out to 500 MS
  129. Sp. ReadTimeout = 500;
  130. }
  131. Catch(System. Exception ex)
  132. {
  133. BaudRatelLabel. Text = ex. Message;
  134. }
  135. }
  136. }
  137. }

Code of the dialog box for setting properties of the C # serial communication program:

  1. # Region Using directives
  2.  
  3. UsingSystem;
  4. UsingSystem. Collections. Generic;
  5. UsingSystem. ComponentModel;
  6. UsingSystem. Data;
  7. UsingSystem. Drawing;
  8. UsingSystem. Text;
  9. UsingSystem. Windows. Forms;
  10.  
  11. # Endregion
  12.  
  13. NamespaceSerialexpample
  14. {
  15. PartialClassPropertyPage: Form
  16. {
  17. // Variables for storing values of baud rate and stop bits
  18. Private StringBaudR = "";
  19. Private StringStopB = "";
  20.  
  21. // Property for setting and getting baud rate and stop bits
  22. Public StringBRate
  23. {
  24. Get 
  25. {
  26. ReturnBaudR;
  27. }
  28. Set 
  29. {
  30. BaudR = value;
  31. }
  32. }
  33.  
  34. Public StringSBits
  35. {
  36. Get 
  37. {
  38. ReturnStopB;
  39. }
  40. Set 
  41. {
  42. StopB = value;
  43. }
  44. }
  45.  
  46. PublicPropertyPage ()
  47. {
  48. InitializeComponent ();
  49. }
  50.  
  51. Private VoidCancelButton_Click (
  52. ObjectSender, EventArgs e)
  53. {
  54. This. BRate = "";
  55. This. SBits = "";
  56. // Close form
  57. This. Close ();
  58. }
  59.  
  60. Private VoidOkButton_Click_1 (
  61. ObjectSender, EventArgs e)
  62. {
  63. // Here we set the value for stop bits and baud rate.
  64. This. BRate = BaudRateComboBox. Text;
  65. This. SBits = stopBitComboBox. Text;
  66. //
  67. This. Close ();
  68.  
  69. }
  70. }
  71. }

This section describes how to create a C # serial communication program.


How to Create a C file in VS2010

Open VS2010, file -- New -- Project, select the Win32 console application in Visual C ++, enter the following name (such as New Project), and click OK.
2. Go to the Win32 Application Wizard, click Next, and select "Empty Project" in application settings.
3. find the "source file" in the left-side table, right-click, add -- new item -- C ++ file, and fill in the following name with the suffix. C (such as My file. c), and then click Add. OK. You can compile your C program.

 
How to create a window in C Language

# Include <windows. h>
Lresult callback WndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam );
Int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR sz1_line, int iCmdShow)
{
Static TCHAR szAppName [] = TEXT ("OLS ");
HWND hwnd;
MSG msg;
WNDCLASSEX wndclassex = {0 };
Wndclassex. cbSize = sizeof (WNDCLASSEX );
Wndclassex. style = CS_HREDRAW | CS_VREDRAW;
Wndclassex. lpfnWndProc = WndProc;
Wndclassex. cbClsExtra = 0;
Wndclassex. cbWndExtra = 0;
Wndclassex. hInstance = hInstance;
Wndclassex. hIcon = LoadIcon (NULL, IDI_APPLICATION );
Wndclassex. hCursor = LoadCursor (NULL, IDC_ARROW );
Wndclassex. hbrBackground = (HBRUSH) GetStockObject (WHITE_BRUSH );
Wndclassex. lpszMenuName = NULL;
Wndclassex. lpszClassName = szAppName;
Wndclassex. hIconSm = wndclassex. hIcon;

If (! RegisterClassEx (& wndclassex ))
{
MessageBox (NULL, TEXT ("RegisterClassEx failed! "), SzAppName, MB_ICONERROR );
Return 0;
}
Hwnd = createmediawex (WS_EX_OVERLAPPEDWINDOW,
SzAppName,
TEXT ("WindowTitle "),
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
NULL,
NULL,
HInstance,
... The remaining full text>

Related Article

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.