C#.NET merupakan salah satu bahasa pemrograman terbaik, dengan tersedianya IDE yang tepat, Microsoft Visual Studio .NET, menggunakan .NET Framework 2.x

Kali ini kita belajar membaca data dari Serial Port. Pemrograman Serial biasanya dipakai untuk mendapatkan data dari Jembatan Timbang, Timbangan basis “Mini PC” dan sejenisnya.

Buatlah class yang menampung semua metode / prosedur membaca, mengolah transaksi timbangan, misalkan kita buat project bernama CapellaUtility, dengan class Utility, seperti code dibawah ini

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.IO.Ports;

namespace CapellaUtility {
  public class Utility {
    private static SerialPort port = new SerialPort("COM3",
      9600, Parity.None, 8, StopBits.One);
    public static Double PortReturnValue;
    private static String PortValue;

    public static void SerialPort(string PortName, int BaudRate, string ParityType, int ParityBit, string ParityStopBit) {
      try {
        port.Close();
      } catch (Exception ex) {
      }
      Parity ParityValue = Parity.None;
      StopBits ParityStopBits = StopBits.None;
      switch (ParityType) {
        case "None":
          ParityValue = Parity.None;
          break;
        case "Even":
          ParityValue = Parity.Even;
          break;
        case "Mark":
          ParityValue = Parity.Mark;
          break;
        case "Odd":
          ParityValue = Parity.Odd;
          break;
        case "Space":
          ParityValue = Parity.Space;
          break;
        default:
          break;
      }
      switch (ParityStopBit) {
        case "None":
          ParityStopBits = StopBits.None;
          break;
        case "One":
          ParityStopBits = StopBits.One;
          break;
        case "OnePointFive":
          ParityStopBits = StopBits.OnePointFive;
          break;
        case "Two":
          ParityStopBits = StopBits.Two;
          break;
        default:
          break;
      }
      port = new SerialPort(PortName, BaudRate, ParityValue, ParityBit, ParityStopBits);
      port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
    }

    public static void GetSerialPort() {
      try {
        port.Close();
      } catch (Exception ex) {
      }
      port.Open();
    }

    private static void port_DataReceived(object sender, SerialDataReceivedEventArgs e) {
      try {
        PortValue = port.ReadLine();
        if (PortValue.Contains("ST")) {
            PortValue = PortValue.Replace("ST", "");
            PortValue = PortValue.Replace("GS", "");
            PortValue = PortValue.Replace(",", "");
            PortValue = PortValue.Replace("+", "");
            PortValue = PortValue.Replace("kg", "");
            PortValue = PortValue.Replace("\r", "");
            PortReturnValue = Convert.ToDouble(PortValue);
        }
      } catch (Exception ex) {
      }
    }

    public static string[] GetPortNames() {
      return System.IO.Ports.SerialPort.GetPortNames();
    }
  }
}
Kemudian kita buat User Interfacenya sebagai berikut :

File Mainform.cs

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

namespace libramas
{
    public partial class MainForm : Form
    {
      public MainForm()
      {
          InitializeComponent();
      }

      private void tiMain_Tick(object sender, EventArgs e)
      {
        try {
          CapellaUtility.Utility.GetSerialPort();
          txtBerat.Text = CapellaUtility.Utility.PortReturnValue.ToString();
        } catch (Exception ex) {
        }
      }

      private void btnRun_Click(object sender, EventArgs e)
      {
        try {
          tiMain.Enabled = false;
          CapellaUtility.Utility.SerialPort(txtPorts.Text, (int)txtBaudRate.Value,
            txtParity.Text, (int)txtBit.Value, txtStopBits.Text);
          tiMain.Enabled = true;
        } catch (Exception ex) {
        }
      }

      private void MainForm_Load(object sender, EventArgs e)
      {
        txtParity.Text = "Even";
        txtStopBits.Text = "One";
        txtPorts.Items.AddRange(CapellaUtility.Utility.GetPortNames());
        if (txtPorts.Items.Count > 0) {
          txtPorts.SelectedIndex = 0;
        }
      }
    }
}
File Mainform.resx

<?xml version="1.0" encoding="utf-8"?>
<root>
  <!-- 
    Microsoft ResX Schema 
    
    Version 2.0
    
    The primary goals of this format is to allow a simple XML format 
    that is mostly human readable. The generation and parsing of the 
    various data types are done through the TypeConverter classes 
    associated with the data types.
    
    Example:
    
    ... ado.net/XML headers & schema ...
    <resheader name="resmimetype">text/microsoft-resx</resheader>
    <resheader name="version">2.0</resheader>
    <resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
    <resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
    <data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
    <data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
    <data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
        <value>[base64 mime encoded serialized .NET Framework object]</value>
    </data>
    <data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
        <value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
        <comment>This is a comment</comment>
    </data>
                
    There are any number of "resheader" rows that contain simple 
    name/value pairs.
    
    Each data row contains a name, and value. The row also contains a 
    type or mimetype. Type corresponds to a .NET class that support 
    text/value conversion through the TypeConverter architecture. 
    Classes that don't support this are serialized and stored with the 
    mimetype set.
    
    The mimetype is used for serialized objects, and tells the 
    ResXResourceReader how to depersist the object. This is currently not 
    extensible. For a given mimetype the value must be set accordingly:
    
    Note - application/x-microsoft.net.object.binary.base64 is the format 
    that the ResXResourceWriter will generate, however the reader can 
    read any of the formats listed below.
    
    mimetype: application/x-microsoft.net.object.binary.base64
    value   : The object must be serialized with 
            : System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
            : and then encoded with base64 encoding.
    
    mimetype: application/x-microsoft.net.object.soap.base64
    value   : The object must be serialized with 
            : System.Runtime.Serialization.Formatters.Soap.SoapFormatter
            : and then encoded with base64 encoding.

    mimetype: application/x-microsoft.net.object.bytearray.base64
    value   : The object must be serialized into a byte array 
            : using a System.ComponentModel.TypeConverter
            : and then encoded with base64 encoding.
    -->
  <xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
    <xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
    <xsd:element name="root" msdata:IsDataSet="true">
      <xsd:complexType>
        <xsd:choice maxOccurs="unbounded">
          <xsd:element name="metadata">
            <xsd:complexType>
              <xsd:sequence>
                <xsd:element name="value" type="xsd:string" minOccurs="0" />
              </xsd:sequence>
              <xsd:attribute name="name" use="required" type="xsd:string" />
              <xsd:attribute name="type" type="xsd:string" />
              <xsd:attribute name="mimetype" type="xsd:string" />
              <xsd:attribute ref="xml:space" />
            </xsd:complexType>
          </xsd:element>
          <xsd:element name="assembly">
            <xsd:complexType>
              <xsd:attribute name="alias" type="xsd:string" />
              <xsd:attribute name="name" type="xsd:string" />
            </xsd:complexType>
          </xsd:element>
          <xsd:element name="data">
            <xsd:complexType>
              <xsd:sequence>
                <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
                <xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
              </xsd:sequence>
              <xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
              <xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
              <xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
              <xsd:attribute ref="xml:space" />
            </xsd:complexType>
          </xsd:element>
          <xsd:element name="resheader">
            <xsd:complexType>
              <xsd:sequence>
                <xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
              </xsd:sequence>
              <xsd:attribute name="name" type="xsd:string" use="required" />
            </xsd:complexType>
          </xsd:element>
        </xsd:choice>
      </xsd:complexType>
    </xsd:element>
  </xsd:schema>
  <resheader name="resmimetype">
    <value>text/microsoft-resx</value>
  </resheader>
  <resheader name="version">
    <value>2.0</value>
  </resheader>
  <resheader name="reader">
    <value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
  </resheader>
  <resheader name="writer">
    <value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
  </resheader>
  <metadata name="tiMain.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
    <value>121, 17</value>
  </metadata>
</root>
File Mainform.Designer

namespace libramas
{
    partial class MainForm
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #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>
        private void InitializeComponent()
        {
            this.components = new System.ComponentModel.Container();
            this.tiMain = new System.Windows.Forms.Timer(this.components);
            this.txtBerat = new System.Windows.Forms.TextBox();
            this.lbPort = new System.Windows.Forms.Label();
            this.lbBaudRate = new System.Windows.Forms.Label();
            this.txtBaudRate = new System.Windows.Forms.NumericUpDown();
            this.lbParity = new System.Windows.Forms.Label();
            this.txtParity = new System.Windows.Forms.ComboBox();
            this.txtBit = new System.Windows.Forms.NumericUpDown();
            this.lbBit = new System.Windows.Forms.Label();
            this.txtStopBits = new System.Windows.Forms.ComboBox();
            this.lbStopBit = new System.Windows.Forms.Label();
            this.btnRun = new System.Windows.Forms.Button();
            this.txtPorts = new System.Windows.Forms.ComboBox();
            ((System.ComponentModel.ISupportInitialize)(this.txtBaudRate)).BeginInit();
            ((System.ComponentModel.ISupportInitialize)(this.txtBit)).BeginInit();
            this.SuspendLayout();
            // 
            // tiMain
            // 
            this.tiMain.Interval = 1000;
            this.tiMain.Tick += new System.EventHandler(this.tiMain_Tick);
            // 
            // txtBerat
            // 
            this.txtBerat.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.txtBerat.Dock = System.Windows.Forms.DockStyle.Bottom;
            this.txtBerat.Enabled = false;
            this.txtBerat.Font = new System.Drawing.Font("Microsoft Sans Serif", 48F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.txtBerat.Location = new System.Drawing.Point(0, 188);
            this.txtBerat.Name = "txtBerat";
            this.txtBerat.ReadOnly = true;
            this.txtBerat.Size = new System.Drawing.Size(292, 80);
            this.txtBerat.TabIndex = 1;
            this.txtBerat.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
            // 
            // lbPort
            // 
            this.lbPort.AutoSize = true;
            this.lbPort.Location = new System.Drawing.Point(13, 13);
            this.lbPort.Name = "lbPort";
            this.lbPort.Size = new System.Drawing.Size(26, 13);
            this.lbPort.TabIndex = 2;
            this.lbPort.Text = "Port";
            // 
            // lbBaudRate
            // 
            this.lbBaudRate.AutoSize = true;
            this.lbBaudRate.Location = new System.Drawing.Point(13, 39);
            this.lbBaudRate.Name = "lbBaudRate";
            this.lbBaudRate.Size = new System.Drawing.Size(58, 13);
            this.lbBaudRate.TabIndex = 4;
            this.lbBaudRate.Text = "Baud Rate";
            // 
            // txtBaudRate
            // 
            this.txtBaudRate.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.txtBaudRate.Location = new System.Drawing.Point(77, 39);
            this.txtBaudRate.Maximum = new decimal(new int[] {
            100000,
            0,
            0,
            0});
            this.txtBaudRate.Name = "txtBaudRate";
            this.txtBaudRate.Size = new System.Drawing.Size(120, 20);
            this.txtBaudRate.TabIndex = 6;
            this.txtBaudRate.Value = new decimal(new int[] {
            2400,
            0,
            0,
            0});
            // 
            // lbParity
            // 
            this.lbParity.AutoSize = true;
            this.lbParity.Location = new System.Drawing.Point(13, 65);
            this.lbParity.Name = "lbParity";
            this.lbParity.Size = new System.Drawing.Size(33, 13);
            this.lbParity.TabIndex = 7;
            this.lbParity.Text = "Parity";
            // 
            // txtParity
            // 
            this.txtParity.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.txtParity.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.txtParity.FormattingEnabled = true;
            this.txtParity.Items.AddRange(new object[] {
            "None",
            "Mark",
            "Even",
            "Odd",
            "Space"});
            this.txtParity.Location = new System.Drawing.Point(77, 66);
            this.txtParity.Name = "txtParity";
            this.txtParity.Size = new System.Drawing.Size(163, 21);
            this.txtParity.TabIndex = 8;
            // 
            // txtBit
            // 
            this.txtBit.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.txtBit.Location = new System.Drawing.Point(77, 93);
            this.txtBit.Maximum = new decimal(new int[] {
            100000,
            0,
            0,
            0});
            this.txtBit.Name = "txtBit";
            this.txtBit.Size = new System.Drawing.Size(120, 20);
            this.txtBit.TabIndex = 10;
            this.txtBit.Value = new decimal(new int[] {
            7,
            0,
            0,
            0});
            // 
            // lbBit
            // 
            this.lbBit.AutoSize = true;
            this.lbBit.Location = new System.Drawing.Point(13, 93);
            this.lbBit.Name = "lbBit";
            this.lbBit.Size = new System.Drawing.Size(19, 13);
            this.lbBit.TabIndex = 9;
            this.lbBit.Text = "Bit";
            // 
            // txtStopBits
            // 
            this.txtStopBits.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.txtStopBits.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.txtStopBits.FormattingEnabled = true;
            this.txtStopBits.Items.AddRange(new object[] {
            "None",
            "One",
            "OnePointFive",
            "Two"});
            this.txtStopBits.Location = new System.Drawing.Point(77, 119);
            this.txtStopBits.Name = "txtStopBits";
            this.txtStopBits.Size = new System.Drawing.Size(163, 21);
            this.txtStopBits.TabIndex = 12;
            // 
            // lbStopBit
            // 
            this.lbStopBit.AutoSize = true;
            this.lbStopBit.Location = new System.Drawing.Point(13, 118);
            this.lbStopBit.Name = "lbStopBit";
            this.lbStopBit.Size = new System.Drawing.Size(44, 13);
            this.lbStopBit.TabIndex = 11;
            this.lbStopBit.Text = "Stop Bit";
            // 
            // btnRun
            // 
            this.btnRun.Location = new System.Drawing.Point(13, 152);
            this.btnRun.Name = "btnRun";
            this.btnRun.Size = new System.Drawing.Size(75, 23);
            this.btnRun.TabIndex = 13;
            this.btnRun.Text = "Submit";
            this.btnRun.UseVisualStyleBackColor = true;
            this.btnRun.Click += new System.EventHandler(this.btnRun_Click);
            // 
            // txtPorts
            // 
            this.txtPorts.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.txtPorts.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
            this.txtPorts.FormattingEnabled = true;
            this.txtPorts.Location = new System.Drawing.Point(77, 12);
            this.txtPorts.Name = "txtPorts";
            this.txtPorts.Size = new System.Drawing.Size(163, 21);
            this.txtPorts.TabIndex = 14;
            // 
            // MainForm
            // 
            this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(292, 268);
            this.Controls.Add(this.txtPorts);
            this.Controls.Add(this.btnRun);
            this.Controls.Add(this.txtStopBits);
            this.Controls.Add(this.lbStopBit);
            this.Controls.Add(this.txtBit);
            this.Controls.Add(this.lbBit);
            this.Controls.Add(this.txtParity);
            this.Controls.Add(this.lbParity);
            this.Controls.Add(this.txtBaudRate);
            this.Controls.Add(this.lbBaudRate);
            this.Controls.Add(this.lbPort);
            this.Controls.Add(this.txtBerat);
            this.Name = "MainForm";
            this.Text = "Capella - Timbangan";
            this.Load += new System.EventHandler(this.MainForm_Load);
            ((System.ComponentModel.ISupportInitialize)(this.txtBaudRate)).EndInit();
            ((System.ComponentModel.ISupportInitialize)(this.txtBit)).EndInit();
            this.ResumeLayout(false);
            this.PerformLayout();

        }

        #endregion

      private System.Windows.Forms.Timer tiMain;
      private System.Windows.Forms.TextBox txtBerat;
      private System.Windows.Forms.Label lbPort;
      private System.Windows.Forms.Label lbBaudRate;
      private System.Windows.Forms.NumericUpDown txtBaudRate;
      private System.Windows.Forms.Label lbParity;
      private System.Windows.Forms.ComboBox txtParity;
      private System.Windows.Forms.NumericUpDown txtBit;
      private System.Windows.Forms.Label lbBit;
      private System.Windows.Forms.ComboBox txtStopBits;
      private System.Windows.Forms.Label lbStopBit;
      private System.Windows.Forms.Button btnRun;
      private System.Windows.Forms.ComboBox txtPorts;
    }
}
File Program.cs

using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace libramas
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainForm());
        }
    }
}
Demikianlah pembuatan aplikasi untuk membaca jembatan timbang, tentu jangan lupa untuk membaca konfigurasi yang disertakan dalam Buku / User Manual alat