C # Serial Communication Programming

Source: Internet
Author: User

C # Serial Communication Programming
IvanxBy
This article describes how to use C # To create a serial communication program on the. NET platform. NET 2.0 provides the serial communication function. Its namespace is System. IO. Ports. We will use standard RS 232C for inter-PC communication...

 

[Translation]
Tapan Dantre. By Serial Communication using C # and Whidbey

[Introduction]

This article describes how to use C # To create a 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.

Namespace

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

Create a SerialPort object

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

Code:

// Create a Serial Port object
SerialPort sp = new SerialPort ();

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.

Serial Port hardware knowledge

During data transmission, each byte of data is transmitted through a single cable. The package includes the start bit, data, and end value. Once the start bit is passed out, data will be transmitted later, which may be 5, 6, 7, or 8 digits. It depends on your settings. The same baud rate and number of data digits must be set for sending and receiving.

Cat-free mode

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

RS232 pin chart

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

[Sample program]

Main Program

If you want to use the default Property, press the Save Status button. If you want to change the Property, press "Property ". It will pop up:

After setting, you can communicate.


Code of the Main Window

Code: 
#region Using directives

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using System.IO.Ports;

#endregion

namespace Serialexpample
{
partial class Form1 : Form
{
//create instance of property page
//property page is used to set values for stop bits and
//baud rate
PropertyPage pp = new PropertyPage();

//create an Serial Port object
SerialPort sp = new SerialPort();

public Form1()
{
InitializeComponent();
}

private void propertyButton_Click(object sender, EventArgs e)
{
//show property dialog
pp.ShowDialog();

propertyButton.Hide();
}

private void sendButton_Click(object sender, 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 void ReadButton_Click(object sender, 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 void Form1_Load(object sender, EventArgs e)
{

}

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
MessageBox.Show("Do u want to Close the App");
sp.Close();
}

private void startCommButton_Click(object sender, EventArgs e)
{
startCommButton.Hide();
sendButton.Show();
readButton.Show();
textBox.Show();
}

//when we want to save the status(value)
private void saveStatusButton_Click_1(object sender, 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;
}

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 property Setting Dialog Box:

Code: 
#region Using directives

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

#endregion

namespace Serialexpample
{
partial class PropertyPage : Form
{
//variables for storing values of baud rate and stop bits
private string baudR="";
private string stopB="";

//property for setting and getting baud rate and stop bits
public string bRate
{
get
{
return baudR;
}
set
{
baudR = value;
}
}

public string sBits
{
get
{
return stopB;
}
set
{
stopB = value;
}
}

public PropertyPage()
{
InitializeComponent();
}

private void cancelButton_Click(object sender, EventArgs e)
{
this.bRate = "";
this.sBits = "";
//close form
this.Close();
}

private void okButton_Click_1(object sender, EventArgs e)
{
//here we set the value for stop bits and baud rate.
this.bRate = BaudRateComboBox.Text;
this.sBits = stopBitComboBox.Text;
//
this.Close();

}
}
}
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.