0% found this document useful (0 votes)
98 views8 pages

Serial Port Programming Guide

The document describes a C# Windows form application for serial port communication. It defines classes and methods for initializing a serial port, sending and receiving data, and handling events like the serial data received event. When data is received, it is displayed in a textbox. Buttons allow sending data and exiting the application, which also closes the serial port. Settings for the serial port like baud rate, data bits, and parity can be configured through combo boxes.

Uploaded by

Thanh Bình
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
98 views8 pages

Serial Port Programming Guide

The document describes a C# Windows form application for serial port communication. It defines classes and methods for initializing a serial port, sending and receiving data, and handling events like the serial data received event. When data is received, it is displayed in a textbox. Buttons allow sending data and exiting the application, which also closes the serial port. Settings for the serial port like baud rate, data bits, and parity can be configured through combo boxes.

Uploaded by

Thanh Bình
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

VC++CLR WINFORM SERIAL PORT

#pragma once

namespace VCSerialPort {

using namespace System;


using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;
using namespace System::IO::Ports;
using namespace System::Threading;

/// <summary>
/// Summary for MyForm
/// </summary>
public ref class MyForm : public System::Windows::Forms::Form
{

public:
MyForm(void)
{
InitializeComponent();
//
//TODO: Add the constructor code here
//
}
public: String^ datain;
protected:
/// <summary>
/// Clean up any resources being used.
/// </summary>
~MyForm()
{
if (components)
{
delete components;
}
}
private: System::Windows::Forms::TextBox^ tbSend;
private: System::Windows::Forms::TextBox^ tbReceive;
protected:
private: System::Windows::Forms::Button^ btSend;
private: System::Windows::Forms::Button^ btExit;
private: System::IO::Ports::SerialPort^ serialPort1;
private: System::Windows::Forms::Label^ label1;
private: System::ComponentModel::IContainer^ components;
protected:

private:
/// <summary>
/// Required designer variable.
/// </summary>

#pragma region Windows Form Designer generated code


/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
void InitializeComponent(void)
{
this->components = (gcnew System::ComponentModel::Container());
this->tbSend = (gcnew System::Windows::Forms::TextBox());
this->tbReceive = (gcnew System::Windows::Forms::TextBox());
this->btSend = (gcnew System::Windows::Forms::Button());
this->btExit = (gcnew System::Windows::Forms::Button());
this->serialPort1 = (gcnew System::IO::Ports::SerialPort(this-
>components));
this->label1 = (gcnew System::Windows::Forms::Label());
this->SuspendLayout();
//
// tbSend
//
this->tbSend->Location = System::Drawing::Point(36, 67);
this->tbSend->Name = L"tbSend";
this->tbSend->Size = System::Drawing::Size(100, 22);
this->tbSend->TabIndex = 0;
//
// tbReceive
//
this->tbReceive->Location = System::Drawing::Point(175, 67);
this->tbReceive->Name = L"tbReceive";
this->tbReceive->Size = System::Drawing::Size(83, 22);
this->tbReceive->TabIndex = 1;
//
// btSend
//
this->btSend->Location = System::Drawing::Point(47, 122);
this->btSend->Name = L"btSend";
this->btSend->Size = System::Drawing::Size(75, 23);
this->btSend->TabIndex = 2;
this->btSend->Text = L"SEND";
this->btSend->UseVisualStyleBackColor = true;
this->btSend->Click += gcnew System::EventHandler(this,
&MyForm::btSend_Click);
//
// btExit
//
this->btExit->Location = System::Drawing::Point(183, 122);
this->btExit->Name = L"btExit";
this->btExit->Size = System::Drawing::Size(75, 23);
this->btExit->TabIndex = 3;
this->btExit->Text = L"EXIT";
this->btExit->UseVisualStyleBackColor = true;
this->btExit->Click += gcnew System::EventHandler(this,
&MyForm::btExit_Click);
//
// serialPort1
//
this->serialPort1->PortName = L"COM5";
this->serialPort1->DataReceived += gcnew
System::IO::Ports::SerialDataReceivedEventHandler(this,
&MyForm::serialPort1_DataReceived);
//
// label1
//
this->label1->AutoSize = true;
this->label1->Location = System::Drawing::Point(62, 44);
this->label1->Name = L"label1";
this->label1->Size = System::Drawing::Size(64, 17);
this->label1->TabIndex = 4;
this->label1->Text = L"CLOSED";
//
// MyForm
//
this->AutoScaleDimensions = System::Drawing::SizeF(8, 16);
this->AutoScaleMode =
System::Windows::Forms::AutoScaleMode::Font;
this->ClientSize = System::Drawing::Size(323, 255);
this->Controls->Add(this->label1);
this->Controls->Add(this->btExit);
this->Controls->Add(this->btSend);
this->Controls->Add(this->tbReceive);
this->Controls->Add(this->tbSend);
this->Name = L"MyForm";
this->Text = L"MyForm";
this->Load += gcnew System::EventHandler(this,
&MyForm::MyForm_Load);
this->ResumeLayout(false);
this->PerformLayout();

}
#pragma endregion

private: System::Void MyForm_Load(System::Object^ sender, System::EventArgs^ e)


{
serialPort1->PortName = "COM5";
serialPort1->BaudRate = 9600;
serialPort1->Parity = Parity::None;
serialPort1->StopBits = StopBits::One;
serialPort1->DataBits = 8;
serialPort1->Handshake = Handshake::None;
serialPort1->Open();
if (serialPort1->IsOpen == true) { label1->Text = "OPENED"; }
else
label1->Text = "CLOSED";

}
private: System::Void btSend_Click(System::Object^ sender, System::EventArgs^ e)
{
serialPort1->Write(tbSend->Text);
}
private: System::Void DisplayText(System::Object^ sender, System::EventArgs^ e) {
tbReceive->Text=(datain);
}
private: System::Void serialPort1_DataReceived(System::Object^ sender,
System::IO::Ports::SerialDataReceivedEventArgs^ e)
{
datain = serialPort1->ReadExisting();
this->Invoke(gcnew EventHandler(this, &MyForm::DisplayText));
}
private: System::Void btExit_Click(System::Object^ sender, System::EventArgs^ e)
{
serialPort1->Close();
this->Close();
}
};
}

C#SerialPort

using System;
using System.Windows.Forms;
using System.IO.Ports;
namespace SerialCS
{
public partial class Form1 : Form
{
SerialPort ComPort = new SerialPort();
internal delegate void SerialDataReceivedEventHandlerDelegate(
object sender, SerialDataReceivedEventArgs e);
delegate void SetTextCallback(string text);
string InputData = String.Empty;
int RcvNumber;
Label[] lamp = new Label[8];
public Form1()
{
InitializeComponent();
ComPort.DataReceived +=
new SerialDataReceivedEventHandler(Received_1);
}
private void Exit_Click(object sender, EventArgs e)
{
ComPort.Close();
Application.Exit();
}
private void Settings_Click(object sender, EventArgs e)
{
string[] ArrayComPortsNames = null;
int index = -1;
string ComPortName = null;
//Com Ports
ArrayComPortsNames = SerialPort.GetPortNames();
do
{
index += 1;
cboPorts.Items.Add(ArrayComPortsNames[index]);
}
while (!((ArrayComPortsNames[index] == ComPortName) ||
(index == ArrayComPortsNames.GetUpperBound(0))));
Array.Sort(ArrayComPortsNames);
if (index == ArrayComPortsNames.GetUpperBound(0))
{
ComPortName = ArrayComPortsNames[0];
}
cboPorts.Text = ArrayComPortsNames[0];
//Baud Rate
cboBaudRate.Items.Add(9600);
cboBaudRate.Items.Add(19200);
cboBaudRate.Items.Add(38400);
cboBaudRate.Items.Add(57600);
cboBaudRate.Items.Add(115200);
cboBaudRate.Items.ToString();
//get first item print in text
cboBaudRate.Text = cboBaudRate.Items[0].ToString();
//Data Bits
cboDataBits.Items.Add(7);
cboDataBits.Items.Add(8);
cboDataBits.Text = cboDataBits.Items[0].ToString();
//Stop Bits
cboStopBits.Items.Add("One");
cboStopBits.Items.Add("OnePointFive");
cboStopBits.Items.Add("Two");
cboStopBits.Text = cboStopBits.Items[0].ToString();
//Parity
cboParity.Items.Add("None");
cboParity.Items.Add("Even");
cboParity.Items.Add("Mark");
cboParity.Items.Add("Odd");
cboParity.Items.Add("Space");
cboParity.Text = cboParity.Items[0].ToString();
//Handshake
cboHandShaking.Items.Add("None");
cboHandShaking.Items.Add("XOnXOff");
cboHandShaking.Items.Add("RequestToSend");
cboHandShaking.Items.Add("RequestToSendXOnXOff");
cboHandShaking.Text = cboHandShaking.Items[0].ToString();
}
private void Open_Click(object sender, EventArgs e)
{
if (Open.Text == "CLOSED")
{
ComPort.PortName = Convert.ToString(cboPorts.Text);
ComPort.BaudRate = Convert.ToInt32(cboBaudRate.Text);
ComPort.DataBits = Convert.ToInt16(cboDataBits.Text);
ComPort.StopBits = (StopBits)Enum.Parse(typeof(StopBits),
cboStopBits.Text);
ComPort.Handshake = (Handshake)Enum.Parse(typeof(Handshake),
cboHandShaking.Text);
ComPort.Parity = (Parity)Enum.Parse(typeof(Parity), cboParity.Text);
ComPort.ReadTimeout = 4000;
ComPort.WriteTimeout = 6000;
try
{
ComPort.Open();
if (ComPort.IsOpen)
{
Open.Text = "OPENED";
btSend.Enabled = true;
Settings.Enabled = false;
groupBox1.Enabled = false;
groupBox2.Enabled = false;
}
}
catch (UnauthorizedAccessException ex)
{
MessageBox.Show(ex.Message);
}
}
else if (Open.Text == "OPENED")
{
Open.Text = "CLOSED";
ComPort.Close();
btSend.Enabled = false;
Settings.Enabled = true;
groupBox1.Enabled = true;
groupBox2.Enabled = true;
}
}
private void Received_1(object sender, SerialDataReceivedEventArgs e)
{
if (!rbHex.Checked == true)
{
InputData = ComPort.ReadExisting();
if (InputData != String.Empty)
{
//Show data in Rich Text Box
BeginInvoke(new SetTextCallback(SetText), new object[] { InputData });

}
}
else
{
int number = ComPort.BytesToRead;
byte[] buffer = new byte[number];
ComPort.Read(buffer, 0, number);
String data = BitConverter.ToString(buffer);
//Show received Hex in Rich Text box
BeginInvoke(new SetTextCallback(SetText), new object[] { data });
//Show first byte in TextBox tbDec
int firstbyte = buffer[0];
BeginInvoke(new SetTextCallback(SetTextBox), new object[] {
firstbyte.ToString( )});
//Show 8 bits in color of Labels
int i;
for (i = 7; i >= 0; i--)
{
byte a = buffer[0];
byte c = (byte)(Math.Pow(2, i));
if ((a & c) == c)
lamp[i].BackColor = System.Drawing.Color.Green;
else
lamp[i].BackColor = System.Drawing.Color.Red;

}
}

}
private void SetTextBox(string num)
{
tbDec.Text = num;//Show string in TextBox
}
private void SetText(string text)
{
//Show received Data in Rich Text Box
ReceiveData.Text += text + "\n";//Show string in TextBox

//Show decimal number in Text Box


if (rbDec.Checked == true)
{
try
{
RcvNumber = Convert.ToInt32(text);
tbNumber.Text = RcvNumber.ToString();
}
catch { }
}

}
private void btSend_Click(object sender, EventArgs e)
{
if (!rbHex.Checked == true)
try
{
tbNumber.Text = "";
ComPort.Write(txtSend.Text);
}
catch
{ }
else
{
try
{
byte[] data = StringToByteArray(txtSend.Text);
ComPort.Write(data, 0, data.Length);
}
catch
{ }
}

public static byte[] StringToByteArray(string s)


{
s = s.Replace(" ", "");//delete spaces
byte[] buffer = new byte[s.Length / 2];
for (int i = 0; i< s.Length; i += 2)
buffer[i / 2] = (byte)Convert.ToByte(s.Substring(i, 2), 16);
return buffer;
}
private void rbText_CheckedChanged(object sender, EventArgs e)
{
if (rbText.Checked == false)
{ ComPort.DataBits = 8; cboDataBits.Text = "8"; }
}

private void Form1_Load(object sender, EventArgs e)


{
int i = 0;
//Draw label to show 8 bit value in red and green
for (i = 0; i<8; i++)
{
lamp[i] = new Label();
lamp[i].Text = "";
lamp[i].BackColor = System.Drawing.Color.Red;
lamp[i].Size = new System.Drawing.Size(20, 20);
lamp[i].Location = new System.Drawing.Point(300-i * 30, 350);
this.Controls.Add(lamp[i]);

}
}

You might also like