Introduction

บทความนี้, ผมจะนำเสนอวิธีกาีรเขียนโปรแกรมติดต่อกับ Serial Port บน .NET platform โดยใช้ C# .NET framework version 2.0 ซึ่งมีคุณสมบัติติดต่อกับ serial port ได้. Framework กำหนดให้ใช้ Namespaceชื่อ System.IO.Ports. Framework ใหม่นี้สามารถที่จะติดต่อสื่อสารข้อมูลผ่าน Serial Port บนคอมพิวเตอร์เราได้ และติดต่อกับอุปกรณ์อื่นๆที่ผ่าน Serial port ได้เ่ช่นกัน เราจะใช้ RS 232 C standard สำหรับการติดต่อระหว่าง คอมพิวเตอร์ด้วยกัน ในโหมด full duplex แต่ในที่นี้ผมไม่ได้ใช้ การทำ handshaking หรือ flow control นะครับ ผมจะ้ใช้การต่อแบบ null modem เพื่อการสื่อสารครั้งนี้

สร้าง SerialPort Object

สำหรับการสร้าง object นี้ เราจะสามารถเขียนโปรแกรมเพื่อควบคุมการทำงานของ object นี้ในการติดต่อสื่อสารแบบ Serial Portสมาชิกของ SerialPort class ที่เราจะใช้มีดังนี้

  • ReadLine(): อ่านค่าแบบเป็นบรรทัดแล้วเก็บไว้ใน input buffer. ถ้าไม่มีข้อมูลมาใหม่ก่อนเวลา timeout method นี้จะส่งค่าคืนเป็น  null
  • WriteLine(string): เขียนข้อมูลที่เป็นสตริง และส่งข้อมูลบรรทัดใหม่ไปที่ output buffer.
  • Open(): เปิดการติดต่อ serial port
  • Close(): ปิดการติดต่อ port

Code สำหรับการสร้าง SerialPort object

//สร้าง Serial port object
SerialPort sp = new SerialPort ();

Object นี้มี public constructors 7 ตัว แต่ผมจะใช้แค่ไม่กี่ตัวที่ใช้เป็นกำหนดค่าเริ่มต้นเช่น DataBits กำหนดไว้ที่ 8 และ StopBits กำหนดไว้ที่ 1หมายเลข  Port  กำหนดไว้ที่ Com1The public properties ของ SerialPort class มีดังนี้

  • BaudRate: ตั้งค่าหรือตรวจสอบค่า baud rate.
  • StopBits: ตั้งค่าหรือตรวจสอบค่า stopbits ต่อ byte.
  • ReadTimeout: ตั้งค่าหรือตรวจสอบค่า เวลา timeout ในหน่วย milliseconds ก่อนเกิด timeout เมื่อการอ่านข้มูลทำงานจบ.

มีหลาย public properties แต่จะของแนะนำแค่ 3 ตัวที่กล่าวมาซึ่งตัวอื่นจะเป็นค่า default อยู่แล้วสำหรับการทดสอบโปรแกรมบนเครื่องคอมพิวเตอร์เดียวนั้น ให้ใช้วิธี LoopBack คือ หา DB9 connector มาสักหนึ่งตัว แล้ว ต่อสายระหว่าง Pin 2 กับ 3 เท่านี้ก็ทดลองได้แล้วครับตัวอย่างการเขียนโปรแกรมMain Program

 

แสดงหน้า Properties ถ้าต้องการตั้งค่าใหม่ หลังจากนั้น กด Save Status

 

กด Save Connection  จะแสดงค่าต่างๆ

 

กด Start Connection เพื่อเริ่มการติดต่อ Serial Port 

ทดสอบพิมพ์ข้อความแล้วกด Send Data หลังจากให้ลองกด Read Data
ถ้าการติดต่อสมบูรณ์ ก็จะแสดงข้อความเดิมกลับมา

Code สำหรับ Main Form

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
//เพิ่ม namespace เพื่อเรียกใช้ Serial Port object
using System.IO.Ports;

namespace Serialport_comm
{
 public class Form1 : System.Windows.Forms.Form
 {
  //สร้าง instance ของ property page
  //property page ใช้สำหรับตั้งค่า stopbit  และ  baud rate

  PropertyPage pp = new PropertyPage();
            private TextBox textBox;

  //สร้าง Serial Port object
  SerialPort sp = new SerialPort();

  public Form1()
  {
     InitializeComponent();

  }

  private void Form1_FormClosing(object sender, System.EventArgs  e)
  {
   MessageBox.Show(”คุณต้องการปิดโปรแกรมนี้หรือครับ”);
   sp.Close();
  }

  private void propertyButton_Click(object sender, System.EventArgs e)
  {
   //เปิดหน้า property dialog
   pp.ShowDialog();
   propertyButton.Hide();

  }

  private void sendButton_Click(object sender, System.EventArgs e)
  {
   try
   {
    //เขียนข้อมูลไปที่ 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, System.EventArgs e)
  {
   try
   {
    //clear the text box
    textBox.Text = “”;
    //อ่านค่าจาก  serial port และ แสดง data ใน text box
    textBox.Text = sp.ReadLine();
   }
   catch(System.Exception ex)
   {
    baudRatelLabel.Text = ex.Message;
   }
  }

        private void startCommButton_Click(object sender, System.EventArgs e)
        {
            startCommButton.Hide();
            sendButton.Show();
            readButton.Show();
            textBox.Show();
            baudRatelLabel.Hide();
            dataBitLabel.Hide();
            readTimeOutLabel.Hide();
            stopBitLabel.Hide();
            readTimeOutLabel.Hide();
            parityLabel.Hide();
        }

  private void saveStatusButton_Click(object sender, System.EventArgs e)
  {
   //แสดงค่า
   //ถ้าไม่ใช้ properties จะแสดงค่า defualt
   if (pp.bRate == “” && pp.sBits == “”)
   {
                baudRatelLabel.Text = “BaudRate =” + sp.BaudRate.ToString();
                dataBitLabel.Text = “DataBit = ” + sp.DataBits.ToString();
                readTimeOutLabel.Text = “TimeOut = ” + sp.ReadTimeout.ToString();
   }
   else
   {
                baudRatelLabel.Text = “BaudRate =” + pp.bRate;
                dataBitLabel.Text = “StopBits = ” + pp.sBits;
   }
            parityLabel.Text = “Parity = ” + sp.Parity.ToString();
            stopBitLabel.Text = “StopBit=” + sp.StopBits.ToString();
   readTimeOutLabel.Text = “ReadTimeout = ” + sp.ReadTimeout.ToString();

   if (propertyButton.Visible == true)
    propertyButton.Hide();
   saveStatusButton.Hide();
   startCommButton.Show();

   try
   {
    //open serial port
    sp.Open();
    //กำหนดค่า read time out ที่ 500 ms
    sp.ReadTimeout = 500;
   }
   catch (System.Exception ex)
   {
    baudRatelLabel.Text = ex.Message;
   }

  }
 }
}


Code สำหรับ Property Dialog
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
namespace Serialport_comm
{
 public class PropertyPage : System.Windows.Forms.Form
 {
  public PropertyPage()
  {
   InitializeComponent();
  }

  
        //สร้างตัวแปรสำหรับ Port, baud rate และ stop bits
        private string commPort = “”;
        private string baudR=”";
  private string stopB=”";

        public string CommPort
        {
            get
            {
                return commPort;
            }
            set
            {
                commPort = value;
            }
        }
        public string bRate
  {
   get
   {
    return baudR;
   }
   set
   {
    baudR = value;
   }
  }

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

  private void PropertyPage_Load(object sender, System.EventArgs e)
  {
  
  }

  private void button2_Click(object sender, System.EventArgs e)
  {
   this.bRate = “”;
   this.sBits = “”;
   //ปิด Form
   this.Close();
  }

  private void button1_Click(object sender, System.EventArgs e)
  {
   //เราจะตั้งค่า stop bits และ baud rate.
   this.bRate = BaudRateComboBox.Text;
   this.sBits = stopBitComboBox.Text;
   //ปิด Form
   this.Close();

  }
 
 }
}

Tags: plc ,pac,pc,port,vb,vc,c#,parallel,serial,com,usb