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
- // Create a Serial Port object
- 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
- # Region Using directives
-
- UsingSystem;
- UsingSystem. Collections. Generic;
- UsingSystem. ComponentModel;
- UsingSystem. Data;
- UsingSystem. Drawing;
- UsingSystem. Windows. Forms;
- UsingSystem. IO. Ports;
-
- # Endregion
-
- NamespaceSerialexpample
- {
- PartialClassForm1: Form
- {
- // Create instance of property page
- // Property page is used to set values for stop bits and
- // Baud rate
-
- PropertyPage pp =NewPropertyPage ();
-
- // Create an Serial Port object
- SerialPort sp =NewSerialPort ();
-
- PublicForm1 ()
- {
- InitializeComponent ();
- }
-
- Private VoidPropertyButton_Click (ObjectSender, EventArgs e)
- {
- // Show property dialog
- Pp. ShowDialog ();
-
- PropertyButton. Hide ();
- }
-
- Private VoidSendButton_Click (ObjectSender, EventArgs e)
- {
- Try
- {
- // Write line to serial port
- Sp. WriteLine (textBox. Text );
- // Clear the text box
- TextBox. Text = "";
- }
- Catch(System. Exception ex)
- {
- BaudRatelLabel. Text = ex. Message;
- }
-
- }
-
- Private VoidReadButton_Click (
- ObjectSender, EventArgs e)
- {
- Try
- {
- // Clear the text box
- TextBox. Text = "";
- // Read serial port and displayed the data in text box
- TextBox. Text = sp. ReadLine ();
- }
- Catch(System. Exception ex)
- {
- BaudRatelLabel. Text = ex. Message;
- }
- }
-
- Private VoidForm1_Load (ObjectSender, EventArgs e)
- {
-
- }
-
- Private VoidForm1_FormClosing (
- ObjectSender, FormClosingEventArgs e)
- {
- MessageBox. Show ("Do u want to Close the App ");
- Sp. Close ();
- }
-
- Private VoidStartCommButton_Click (
- ObjectSender, EventArgs e)
- {
- StartCommButton. Hide ();
- SendButton. Show ();
- ReadButton. Show ();
- TextBox. Show ();
- }
-
- // When we want to save the status (value)
- Private VoidSaveStatusButton_Click_1 (
- ObjectSender, EventArgs e)
- {
- // Display values
- // If no property is set the default values
- If(Pp. bRate = "" & pp. sBits = "")
- {
- DataBitLabel. Text = "BaudRate =" +
- Sp. BaudRate. ToString ();
- ReadTimeOutLabel. Text = "StopBits =" +
- Sp. StopBits. ToString ();
- }
- Else
- {
- DataBitLabel. Text = "BaudRate =" +
- Pp. bRate;
- ReadTimeOutLabel. Text = "StopBits =" + pp. sBits;
- } // Create a C # serial communication program
-
- ParityLabel. Text = "DataBits =" +
- Sp. DataBits. ToString ();
- StopBitLabel. Text = "Parity =" +
- Sp. Parity. ToString ();
- ReadTimeOutLabel. Text = "ReadTimeout =" +
- Sp. ReadTimeout. ToString ();
-
- If(PropertyButton. Visible =True)
- PropertyButton. Hide ();
- SaveStatusButton. Hide ();
- StartCommButton. Show ();
-
- Try
- {
- // Open serial port
- Sp. Open ();
- // Set read time out to 500 MS
- Sp. ReadTimeout = 500;
- }
- Catch(System. Exception ex)
- {
- BaudRatelLabel. Text = ex. Message;
- }
- }
- }
- }
Code of the dialog box for setting properties of the C # serial communication program:
- # Region Using directives
-
- UsingSystem;
- UsingSystem. Collections. Generic;
- UsingSystem. ComponentModel;
- UsingSystem. Data;
- UsingSystem. Drawing;
- UsingSystem. Text;
- UsingSystem. Windows. Forms;
-
- # Endregion
-
- NamespaceSerialexpample
- {
- PartialClassPropertyPage: Form
- {
- // Variables for storing values of baud rate and stop bits
- Private StringBaudR = "";
- Private StringStopB = "";
-
- // Property for setting and getting baud rate and stop bits
- Public StringBRate
- {
- Get
- {
- ReturnBaudR;
- }
- Set
- {
- BaudR = value;
- }
- }
-
- Public StringSBits
- {
- Get
- {
- ReturnStopB;
- }
- Set
- {
- StopB = value;
- }
- }
-
- PublicPropertyPage ()
- {
- InitializeComponent ();
- }
-
- Private VoidCancelButton_Click (
- ObjectSender, EventArgs e)
- {
- This. BRate = "";
- This. SBits = "";
- // Close form
- This. Close ();
- }
-
- Private VoidOkButton_Click_1 (
- ObjectSender, EventArgs e)
- {
- // Here we set the value for stop bits and baud rate.
- This. BRate = BaudRateComboBox. Text;
- This. SBits = stopBitComboBox. Text;
- //
- This. Close ();
-
- }
- }
- }
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>