Serial Programming

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 19

VC++CLR WINFORM SERIAL PORT Project VCSerialPort

//MyForm.cpp

#include "MyForm.h"
using namespace System;
using namespace System::Windows::Forms;
[STAThread]
int main(array<String^>^ args) {
Application::EnableVisualStyles();
Application::SetCompatibleTextRenderingDefault(false);
VCSerialPort::MyForm form;
Application::Run(%form);
}

//MyForm.h

#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 Project SerialCS


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]);

}
}
C# ĐƠN GIẢN MÔ PHỎNG KẾT NỐI PC PIC RS232 ĐIỀU KHIỂN HAI LED

Project Project_Comport1
//Use serialPort on ToolBox
using System;
using System.Windows.Forms;
using System.IO.Ports;

namespace Project_Comport1
{
public partial class Form1 : Form
{

delegate void SetTextCallback(string text);


public Form1()
{
InitializeComponent();
}

private void btt_KetNoi_Click(object sender, EventArgs e)


{
string NamePort;
if (serialPort1.IsOpen == false)
{
serialPort1.Open();
NamePort = serialPort1.PortName;
MessageBox.Show("Bạn đã mở thành công " + NamePort);
serialPort1.Write("Send 0, 1,2, or 3");
btt_KetNoi.Enabled = false;
}

private void btExit_Click(object sender, EventArgs e)


{
if (serialPort1.IsOpen == true)
{
serialPort1.Close();
}
this.Close();

private void btt_Gui_Click(object sender, EventArgs e)


{
if (serialPort1.IsOpen == true)
{
if (cb_LED1.Checked == false && cb_LED2.Checked ==
false)
{
serialPort1.Write("0");
}
if (cb_LED1.Checked == true && cb_LED2.Checked ==
false)
{
serialPort1.Write("1");
}
if (cb_LED1.Checked == false && cb_LED2.Checked ==
true)
{
serialPort1.Write("2");
}
if (cb_LED1.Checked == true && cb_LED2.Checked ==
true)
{
serialPort1.Write("3");
}

}
else
{
MessageBox.Show("Bạn chưa mở cổng COM");
}
}

private void DisplayText(string received)


{
tbRcv.Text = received;
if ((received=="1") || (received == "3") )
{ lbLed1.BackColor = System.Drawing.Color.Blue; }
else { lbLed1.BackColor = System.Drawing.Color.Red; }
if ((received == "2") || (received == "3"))
{ lbLed2.BackColor = System.Drawing.Color.Blue; }
else { lbLed2.BackColor = System.Drawing.Color.Red; }
}

private void serialPort1_DataReceived(object sender,


System.IO.Ports.SerialDataReceivedEventArgs e)
{
String data = serialPort1.ReadExisting();
BeginInvoke(new SetTextCallback(DisplayText), new
object[] {data});

}
}

#include <16f877a.h>
#fuses HS,NOWDT,NOPROTECT,BROWNOUT,PUT,NOLVP
#use delay(clock=20000000)
#use rs232(baud=9600,parity=N,xmit=PIN_C6,rcv=PIN_C7,bits=8)

//============================
void main()
{
char c;
Set_tris_D(0x00);
Output_D(0xFF);
while(1)
{
c = getc();
if(c=='0')
{
output_d(0b11111111);
}
if(c=='1')
{
output_d(0b11111110);
}
if(c=='2')
{
output_d(0b11111101);
}
if(c=='3')
{
output_d(0b11111100);
}
}
}
TRUYỀN FILE GIỮA HAI MÁY
Truyền file giữa hai máy dùng cổng COM bây giờ ít dùng nhưng
nghiên cứu lập trình cũng khá lý thú. Phân biệt truyền file text và
file binary, cài đặt WriteBufferSize và ReadBufferSize đến giá trị
tối đa mong muốn (số chẵn), mặc định là 2048.Cần phải sử dụng kiểu
bắt tay để điều khiển luồng dữ liệu.
Chọn file Text,có đuôi txt,c,…, lưu tên file vào TextBox và
hiển thị nội dung file vào RichTextBox
//Created by Nguyen Duc Thanh
using System;
using System.Windows.Forms;

namespace FileTrasferCS
{
public partial class Form1 : Form
{
delegate void SetTextCallback(string text);
String data;
public Form1()
{
InitializeComponent();
}

private void btSendFile_Click(object sender, EventArgs e)


{
OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() == DialogResult.OK)
{
tbFileSend.Text = ofd.FileName;
rtSend.Text =
System.IO.File.ReadAllText(ofd.FileName);
label1.Text = "Press SEND FILE";
btSend.Enabled = true;
}
}

private void btSend_Click(object sender, EventArgs e)


{
label4.Text = "";

serialPort1.Write(System.IO.File.ReadAllText(this.tbFileSend.Text));
label1.Text = "Send Completed";
}

private void btExit_Click(object sender, EventArgs e)


{
serialPort1.Close();
this.Close();
}

private void Form1_Load(object sender, EventArgs e)


{
serialPort1.WriteBufferSize = (int)Math.Pow(2, 16);//64K
Bytes
serialPort1.ReadBufferSize = (int)Math.Pow(2, 16);//64K
Bytes
serialPort1.Open();
if (serialPort1.IsOpen == true) { label1.Text = "Opened
" + serialPort1.PortName; }
else { label1.Text = "Closed " + serialPort1.PortName; }
string c = Char.ConvertFromUtf32(0x31);
tbFileReceive.Text = "d:/Temp.tmp";
btSend.Enabled = false;
}

private void DisplayText(string received)


{
rtFileRcv.Text += received;
}
private void SaveF(string path)
{
using (System.IO.File.Create(path)) ;
rtFileRcv .SaveFile(path,
RichTextBoxStreamType.RichText);
label4.Text = "File Saved ";
}
private void serialPort1_DataReceived(object sender,
System.IO.Ports.SerialDataReceivedEventArgs e)
{
String datain = serialPort1.ReadExisting();
data += datain;

BeginInvoke(new SetTextCallback(DisplayText), new


object[] { datain });
string c = Char.ConvertFromUtf32(0x31);
string d = datain.Substring(datain.Length - 1, 1);
if (c == d)
{
BeginInvoke(new SetTextCallback(SaveF), new object[]
{ tbFileReceive.Text });

}
}
}
}

You might also like