tut huong dan lap trinh c# voi rs232

Upload: pham-duc-sang

Post on 19-Oct-2015

81 views

Category:

Documents


0 download

DESCRIPTION

dsfsdfsd

TRANSCRIPT

  • Ng ng Hin Hc Vin Hi Qun 2011

    1

    HNG DN VIT PHN MM TEST RS232 CHO VI IU

    KHIN VI VISUAL STUDIO C# 2008

    - Cho cc bn, hm nay ngy 05/08/2011, ang ngh php v nh bun qu khng

    c vic g lm. Nn lm bi TUT hng dn anh em newbie si C# 2008

    giao tip vi vi iu khin.

    - Nh chng ta bit y chi vi iu khin m ko giao tip vi PC th ch c g

    phi ni c. Trn cc din n cng bn lun v vn ny kh nhiu nht l

    vi VB6, VC++ Nhng vi C# th c l l hi t. t ra th ti cng au u khi

    mi lm v ko tm thy ti liu ng .

    - C l im mnh ca C# chng ta ko cn phi ni n na. Bi TUT s i su vo

    phn giao tip cn phn C# cc bn nn c qua v n. Ni chung l n kh d

    tip thu so vi thng VB c k v VC++ phc tp. Bi TUT vit cho newbie nn

    ti rt c gng lm cho n chi tit cc bn d hiu hn.

    - Trc khi vo chng ta s im qua 1 s ni dung trong TUT ny:

    SerialPort vi C#

    1 s hiu ng (phn ng) ca C#

    1. u tin l m VC# ln, v to 1 project mi.

    - File / New / Project

  • Ng ng Hin Hc Vin Hi Qun 2011

    2

    - Chn Windows Forms Application v t tn cho chng. a n cho chng ta 1

    giao din ca lp trnh Form. Ging nh cc bn lm bng VB vy

    2. Tip n l chng ta s xy dng giao din nh hnh bn di

    - Nh hnh trn cu trc rt n gin ch ch ComboBox, Button v TextBox

    - COM, BaudRate, Data Bits, Parity, Stop Bit l cc ComboBox

  • Ng ng Hin Hc Vin Hi Qun 2011

    3

    - Kt ni, Ngt, Xa, Thot v SEND l cc Button

    - Cn li 2 ng trng c vin xung quanh chnh l cc TextBox

    - Chng ta s tin hnh to v t tn cho chng.

    - V nh phi t tn cho chng sau mi ln ko ra

    ToolBox ch cc Control.

    y s dng Common

    Control

    Button lm nt

    nhn

    Combox hp iu

    khin cha cc Text

    TextBox ch vn bn,

    dung hin th d

    liu nhn v truyn i

  • Ng ng Hin Hc Vin Hi Qun 2011

    4

    Tng t nh vy vi cc phn cn li, chng ta s xy dng c giao din

    Properties : Ni

    thay i cc thuc tnh

    ca i tng.

    Tn s c t y. y

    chnh l tn ca i tng.

    Ko xung bn di,

    t tn Text. Tn ny

    s hin th ln Button

  • Ng ng Hin Hc Vin Hi Qun 2011

    5

    Thm 1 cht mm, mui chng ta s c giao din nh hnh bn di

    - Giao din nh vy l xong, phn quan trng chnh l code

  • Ng ng Hin Hc Vin Hi Qun 2011

    6

    - Trc khi n code ta s gii thch ni dung ca giao din cng nh tn ca cc

    control cho tin trong vic tham kho code.

    3. Phn CODE

    using System;

    using System.Collections.Generic;

    using System.ComponentModel;

    using System.Data;

    using System.Drawing;

    using System.Linq;

    using System.Text;

    using System.Windows.Forms;

    // Thm 3 em ny vo l OK, si SerialPort

    using System.IO;

    using System.IO.Ports;

    using System.Xml;

    - Chuyn sang phn code bng cch nhp phi chn viewCode, chng ta s thm 2

    th vin IO v xml vo.

    namespace HIENCLUBVN_RS232

    {

    public partial class Form1 : Form

    {

    SerialPort P = new SerialPort(); // Khai bo 1 Object SerialPort mi.

    string InputData = String.Empty; // Khai bo string buff dng cho

    hin th d liu sau ny.

    cbCom

    cbRate

    cbBits

    cbParity

    cbBit

    btSend

    btNgat

    btThoat

    btKetNoi

    btXoa

    Ci ny

    l lch

    cho p

    thi

    Ca StatusStrip1

    Ca Menu

    txtSend

    txtkq

  • Ng ng Hin Hc Vin Hi Qun 2011

    7

    delegate void SetTextCallback(string text); // Khai bao delegate

    SetTextCallBack voi tham so string

    - Trc mt bn ch quan tm n cu lnh SerialPort P = new SerialPort(); // Khai bo 1 Object SerialPort mi.

    - Bc tip l chng ta to d liu cho cc comboBox, bc ny bn nn copy v

    dn vo project ca mnh nh thay tn cc combo cho ng vi tn m bn t.

    public Form1()

    {

    InitializeComponent();

    // Ci t cc thng s cho COM

    // Mng string port ch tt c cc cng COM ang c trn my

    tnh

    string[] ports = SerialPort.GetPortNames();

    // Thm ton b cc COM tm c vo combox cbCom

    cbCom.Items.AddRange(ports); // S dng AddRange thay v dng

    foreach

    P.ReadTimeout = 1000;

    // Khai bo hm delegate bng phng thc DataReceived ca Object

    SerialPort;

    // Ci ny khi c s kin nhn d liu s nhy n phng thc

    DataReceive

    // Nu ko hiu on ny bn c th tm hiu v Delegate, cn ko

    c COPY . Ko cn quan tm

    P.DataReceived += new SerialDataReceivedEventHandler(DataReceive);

    // Ci t cho BaudRate

    string[] BaudRate = { "1200", "2400", "4800", "9600", "19200",

    "38400", "57600", "115200" };

    cbRate.Items.AddRange(BaudRate);

    // Ci t cho DataBits

    string[] Databits = { "6", "7", "8" };

    cbBits.Items.AddRange(Databits);

    //Cho Parity

    string[] Parity = { "None", "Odd", "Even" };

    cbParity.Items.AddRange(Parity);

    //Cho Stop bit

    string[] stopbit = { "1", "1.5", "2" };

    cbBit.Items.AddRange(stopbit);

    // My ci ny kh n gin, bn ng hi v sao. c COPY paste

    cho nhanh. :D

    }

    Bn nn lu l :

    public Form1()

    {

  • Ng ng Hin Hc Vin Hi Qun 2011

    8

    InitializeComponent();

    c to ra trc bi C#, chng ta Copy, Paste th phi sau hm khi to InitializeComponent();

    Ni chung, c bn n y l xong phn khi to cc combox cho SerialPort ri.

    n y bn c th ci t cc thng s cho rs232 bng tay, nu lm ci ny th rs232 c

    th gi l Full, v ta c th hon ton lm ch n v nhng ci nh nht.

    Lc p vo ta to ra 1 s kin l khi thay i cc gi tr trn combo th chng s c

    gi n hm phc v, v cng vic ca chng ta s l y.

    private void cbCom_SelectedIndexChanged(object sender, EventArgs e)

    {

    if (P.IsOpen)

    {

    P.Close(); // Nu ang m Port th phi ng li

    }

    P.PortName = cbCom.SelectedItem.ToString(); // Gn PortName bng

    COM chn

    }

    - Nh v d trn l s gi n hm gn gi tr cng ang chn cho PortName

    - Tng t nh vy chng ta s lm cho ton b comboBox, cc bn c th tham

    kho code di hiu r hn.

    private void cbCom_SelectedIndexChanged(object sender, EventArgs e)

    {

    if (P.IsOpen)

    {

    Nhp chut

    vo y

    Ri vo y.

    Chnh l cc

    s kin m 1

    combo c

    th c.

    p chut

    vo y. Lc

    u n ko c

    ch, p vo

    s c.

  • Ng ng Hin Hc Vin Hi Qun 2011

    9

    P.Close(); // Nu ang m Port th phi ng li

    }

    P.PortName = cbCom.SelectedItem.ToString(); // Gn PortName bng

    COM chn

    }

    private void cbRate_SelectedIndexChanged(object sender, EventArgs e)

    {

    if (P.IsOpen)

    {

    P.Close();

    }

    P.BaudRate = Convert.ToInt32(cbRate.Text);

    }

    private void cbBits_SelectedIndexChanged(object sender, EventArgs e)

    {

    if (P.IsOpen)

    {

    P.Close();

    }

    P.DataBits = Convert.ToInt32(cbBits.Text);

    }

    private void cbParity_SelectedIndexChanged(object sender, EventArgs e)

    {

    if (P.IsOpen)

    {

    P.Close();

    }

    // Vi thng Parity hn lng nhng. Nhng cng OK thi. ^_^

    switch (cbParity.SelectedItem.ToString())

    {

    case "Odd":

    P.Parity = Parity.Odd;

    break;

    case "None":

    P.Parity = Parity.None;

    break;

    case "Even":

    P.Parity = Parity.Even;

    break;

    }

    }

    private void cbBit_SelectedIndexChanged(object sender, EventArgs e)

    {

    if (P.IsOpen)

    {

    P.Close();

    }

    switch (cbBit.SelectedItem.ToString())

    {

    case "1":

    P.StopBits = StopBits.One;

    break;

  • Ng ng Hin Hc Vin Hi Qun 2011

    10

    case "1.5":

    P.StopBits = StopBits.OnePointFive;

    break;

    case "2":

    P.StopBits = StopBits.Two;

    break;

    }

    }

    Vy l xong. Cng vic khi to hon tt, cn by gi l cng vic quan trng

    nht. chnh l xy dng cc hm, th tc cho vic nhn v truyn d liu qua COM

    // Hm ny c s kin nhn d liu gi n. Mc ch hin th thi

    private void DataReceive(object obj, SerialDataReceivedEventArgs e)

    {

    InputData = P.ReadExisting();

    if (InputData != String.Empty)

    {

    // txtIn.Text = InputData; // Ko dng c nh th ny v khc

    threads .

    SetText(InputData); // Chnh v vy phi s dng y quyn ti

    y. Gi delegate khai bo trc .

    }

    }

    // Hm ca em n l y. ng hi v sao li th.

    private void SetText(string text)

    {

    if (this.txtkq.InvokeRequired)

    {

    SetTextCallback d = new SetTextCallback(SetText); // khi to

    1 delegate mi gi n SetText

    this.Invoke(d, new object[] { text });

    }

    else this.txtkq.Text += text;

    }

    // Ton b ci ny bn nn COPY, n cng lm ti au u. :D

    n y l phn nhn xong, tip n phn gi d liu i. Bn nhp p vo button

    SEND, ly s kin ri vit hm theo bn di

    // n hm gi data xung COM

    private void btSend_Click(object sender, EventArgs e)

    {

    if (P.IsOpen)

    {

    if (txtSend.Text == "") MessageBox.Show("Cha c d

    liu!","Thng Bo");

    else P.Write(txtSend.Text);

    }

    else MessageBox.Show("COM cha m.", "Thng bo",

    MessageBoxButtons.OK, MessageBoxIcon.Error);

    txtSend.Clear();

    }

    // n y coi nh mi vic ngon lnh cnh o ri.

  • Ng ng Hin Hc Vin Hi Qun 2011

    11

    // chn tin trong vic Test th chng ta s lm thm bc na.

    cho my ci thng s hay dng c chn. Ko cn thit nu bn cm thy ko

    cn.

    private void Form1_Load(object sender, EventArgs e) // s c gi khi m

    chng trnh.

    {

    cbCom.SelectedIndex = 0; // chn COM c tm thy u tin

    cbRate.SelectedIndex = 3; // 9600

    cbBits.SelectedIndex = 2; // 8

    cbParity.SelectedIndex = 0; // None

    cbBit.SelectedIndex = 0; // None

    // Hin th Status cho Pro t

    status.Text = "Hy chn 1 cng COM kt ni.";

    }

    Bc cui cng l gii quyt 4 button cn li kt ni, ngt kt ni, thot khi chng trnh v xa d liu c. Bc ny kh n gin bn ch vic nhp p vo tng button ly s kin, c th tham kho code di. private void btKetNoi_Click(object sender, EventArgs e)

    {

    try

    {

    P.Open();

    btNgat.Enabled = true;

    btKetNoi.Enabled = false;

    // Hin th Status

    status.Text = "ang kt ni vi cng " +

    cbCom.SelectedItem.ToString();

    }

    catch (Exception ex)

    {

    MessageBox.Show("Khng kt ni c.","Th

    li",MessageBoxButtons.OK,MessageBoxIcon.Error);

    }

    }

    private void btNgat_Click(object sender, EventArgs e)

    {

    P.Close();

    btKetNoi.Enabled = true;

    btNgat.Enabled = false;

    // Hin th Status

    p chut vo thanh tiu

    ly s kin Load. Hm ny s

    c gi ngay khi khi ng.

  • Ng ng Hin Hc Vin Hi Qun 2011

    12

    status.Text = " Ngt Kt Ni";

    }

    private void btThoat_Click(object sender, EventArgs e)

    {

    DialogResult kq = MessageBox.Show("Bn thc s mun thot",

    "HIENCLUBVN", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

    if (kq == DialogResult.Yes)

    {

    MessageBox.Show("Cm n bn s dng chng

    trnh","HIENCLUBVN");

    this.Close();

    }

    }

    private void btXoa_Click(object sender, EventArgs e)

    {

    txtkq.Text = "";

    txtSend.Text = "";

    }

    n y l mi vic ngon lnh cnh o ri. c nhn ha chng trnh ca mnh bn c th thm cc label nh v d l : HC VIN HI QUN hay l menu nh Tc Gi v 1 s hiu ng khc mang tnh chuyn nghip Profectional hn :D

    - Bng cch l thm 1 project mi: Project / Add Windows Form V to n theo mu l mnh u . Cui cng l thm hm s kin khi nhn vo tc gi nh code di. private void aboutToolStripMenuItem_Click(object sender, EventArgs e)

    {

    Form2 frm = new Form2();

    frm.ShowDialog();

    }

    // Lu : Tc Gi l 1 control ca ToolStripMenu bn c th li n ra t

    Toolbox

  • Ng ng Hin Hc Vin Hi Qun 2011

    13

    Lu : Nhn F6 bin dch li trong qu trnh code v F5 chy chng trnh.

    4. Ton b code tin tham kho using System;

    using System.Collections.Generic;

    using System.ComponentModel;

    using System.Data;

    using System.Drawing;

    using System.Linq;

    using System.Text;

    using System.Windows.Forms;

    // Thm 3 em ny vo l OK, si SerialPort

    using System.IO;

    using System.IO.Ports;

    using System.Xml;

    // Bt u code

    namespace HIENCLUBVN_RS232

    {

    public partial class Form1 : Form

    {

    SerialPort P = new SerialPort(); // Khai bo 1 Object SerialPort mi.

    string InputData = String.Empty; // Khai bo string buff dng cho

    hin th d liu sau ny.

    delegate void SetTextCallback(string text); // Khai bao delegate

    SetTextCallBack voi tham so string

    public Form1()

    {

    InitializeComponent();

    // Ci t cc thng s cho COM

    // Mng string port ch tt c cc cng COM ang c trn my

    tnh

    string[] ports = SerialPort.GetPortNames();

    // Thm ton b cc COM tm c vo combox cbCom

    cbCom.Items.AddRange(ports); // S dng AddRange thay v dng

    foreach

    P.ReadTimeout = 1000;

    // Khai bo hm delegate bng phng thc DataReceived ca Object

    SerialPort;

    // Ci ny khi c s kin nhn d liu s nhy n phng thc

    DataReceive

    // Nu ko hiu on ny bn c th tm hiu v Delegate, cn ko

    c COPY . Ko cn quan tm

  • Ng ng Hin Hc Vin Hi Qun 2011

    14

    P.DataReceived += new

    SerialDataReceivedEventHandler(DataReceive);

    // Ci t cho BaudRate

    string[] BaudRate = { "1200", "2400", "4800", "9600", "19200",

    "38400", "57600", "115200" };

    cbRate.Items.AddRange(BaudRate);

    // Ci t cho DataBits

    string[] Databits = { "6", "7", "8" };

    cbBits.Items.AddRange(Databits);

    //Cho Parity

    string[] Parity = { "None", "Odd", "Even" };

    cbParity.Items.AddRange(Parity);

    //Cho Stop bit

    string[] stopbit = { "1", "1.5", "2" };

    cbBit.Items.AddRange(stopbit);

    // My ci ny kh n gin, bn ng hi v sao. c COPY paste

    cho nhanh. :D

    }

    private void cbCom_SelectedIndexChanged(object sender, EventArgs e)

    {

    if (P.IsOpen)

    {

    P.Close(); // Nu ang m Port th phi ng li

    }

    P.PortName = cbCom.SelectedItem.ToString(); // Gn PortName bng

    COM chn

    }

    private void cbRate_SelectedIndexChanged(object sender, EventArgs e)

    {

    if (P.IsOpen)

    {

    P.Close();

    }

    P.BaudRate = Convert.ToInt32(cbRate.Text);

    }

    private void cbBits_SelectedIndexChanged(object sender, EventArgs e)

    {

    if (P.IsOpen)

    {

    P.Close();

    }

    P.DataBits = Convert.ToInt32(cbBits.Text);

    }

    private void cbParity_SelectedIndexChanged(object sender, EventArgs

    e)

    {

    if (P.IsOpen)

    {

    P.Close();

  • Ng ng Hin Hc Vin Hi Qun 2011

    15

    }

    // Vi thng Parity hn lng nhng. Nhng cng OK thi. ^_^

    switch (cbParity.SelectedItem.ToString())

    {

    case "Odd":

    P.Parity = Parity.Odd;

    break;

    case "None":

    P.Parity = Parity.None;

    break;

    case "Even":

    P.Parity = Parity.Even;

    break;

    }

    }

    private void cbBit_SelectedIndexChanged(object sender, EventArgs e)

    {

    if (P.IsOpen)

    {

    P.Close();

    }

    switch (cbBit.SelectedItem.ToString())

    {

    case "1":

    P.StopBits = StopBits.One;

    break;

    case "1.5":

    P.StopBits = StopBits.OnePointFive;

    break;

    case "2":

    P.StopBits = StopBits.Two;

    break;

    }

    }

    // Hm ny c s kin nhn d liu gi n. Mc ch hin th

    thi

    private void DataReceive(object obj, SerialDataReceivedEventArgs e)

    {

    InputData = P.ReadExisting();

    if (InputData != String.Empty)

    {

    // txtIn.Text = InputData; // Ko dng c nh th ny v khc

    threads .

    SetText(InputData); // Chnh v vy phi s dng y quyn ti

    y. Gi delegate khai bo trc .

    }

    }

    // Hm ca em n l y. ng hi v sao li th.

    private void SetText(string text)

    {

    if (this.txtkq.InvokeRequired)

    {

    SetTextCallback d = new SetTextCallback(SetText); // khi to

    1 delegate mi gi n SetText

    this.Invoke(d, new object[] { text });

  • Ng ng Hin Hc Vin Hi Qun 2011

    16

    }

    else this.txtkq.Text += text;

    }

    // Ton b ci ny bn nn COPY, n cng lm ti au u. :D

    // n hm gi data xung COM

    private void btSend_Click(object sender, EventArgs e)

    {

    if (P.IsOpen)

    {

    if (txtSend.Text == "") MessageBox.Show("Cha c d

    liu!","Thng Bo");

    else P.Write(txtSend.Text);

    }

    else MessageBox.Show("COM cha m.", "Thng bo",

    MessageBoxButtons.OK, MessageBoxIcon.Error);

    txtSend.Clear();

    }

    // n y coi nh mi vic ngon lnh cnh o ri.

    // chn tin trong vic Test th chng ta s lm thm bc na.

    cho my ci thng s

    // hay dng c chn. Ko cn thit nu bn cm thy ko cn.

    private void Form1_Load(object sender, EventArgs e) // s c gi

    khi m chng trnh.

    {

    cbCom.SelectedIndex = 0;

    cbRate.SelectedIndex = 3; // 9600

    cbBits.SelectedIndex = 2; // 8

    cbParity.SelectedIndex = 0; // None

    cbBit.SelectedIndex = 0; // None

    // Hin th Status cho Pro t

    status.Text = "Hy chn 1 cng COM kt ni.";

    }

    private void btKetNoi_Click(object sender, EventArgs e)

    {

    try

    {

    P.Open();

    btNgat.Enabled = true;

    btKetNoi.Enabled = false;

    // Hin th Status

    status.Text = "ang kt ni vi cng " +

    cbCom.SelectedItem.ToString();

    }

    catch (Exception ex)

    {

    MessageBox.Show("Khng kt ni c.","Th

    li",MessageBoxButtons.OK,MessageBoxIcon.Error);

    }

    }

    private void btNgat_Click(object sender, EventArgs e)

    {

    P.Close();

    btKetNoi.Enabled = true;

    btNgat.Enabled = false;

  • Ng ng Hin Hc Vin Hi Qun 2011

    17

    // Hin th Status

    status.Text = " Ngt Kt Ni";

    }

    private void btThoat_Click(object sender, EventArgs e)

    {

    DialogResult kq = MessageBox.Show("Bn thc s mun thot",

    "HIENCLUBVN", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

    if (kq == DialogResult.Yes)

    {

    MessageBox.Show("Cm n bn s dng chng

    trnh","HIENCLUBVN");

    this.Close();

    }

    }

    private void btXoa_Click(object sender, EventArgs e)

    {

    txtkq.Text = "";

    txtSend.Text = "";

    }

    private void aboutToolStripMenuItem_Click(object sender, EventArgs e)

    {

    Form2 frm = new Form2();

    frm.ShowDialog();

    }

    }

    }