Sabtu, 12 Desember 2020

Visual C# - Membuat Program Untuk Komunikasi Serial Dengan Mikrokontroler / Arduino

Disini saya menggunakan Ms. Visual C# 2019 Communitty Editions. Program ini berfungsi untuk melakukan komunikasi serial antara PC dengan Arduino atau mikrokontroler. Diantara kegunaannya adalah untuk menyinkronkan waktu modul RTC dengan waktu PC, melakukan Dump Data Remote IR, Debug Program yang telah dibuat, dan lain sebagainya.

Untuk membuat program ini, pertama kali buat desain UI seperti gambar berikut ini:




Adapun komponen yang harus ditambahkan disini adalah tentunya Main Form (Properti Text = komunikasi serial). Kemudian di dalamnya ditambahkan komponen Tab Control, Serial Port, Timer, Status Strip, dan Save File Dialog. Sedangkan di dalam Tab Control memuat komponen-komponen berikut:
  • Tab Page 1
    • Group Box 1 (Text : Waktu)
      • 2 Label
      • 2 Button
    • Groub Box 2 (Text: Kirim Data)
      • 1 Text Box
      • 1 Button
    • Group Box 3 (Text: Data Diterima)
      • 1 Rich Text Box
      • 3 Button
      • 1 Label
  • Tab Page 2
    • 6 Label
    • 6 Combo Box
    • 1 Button
Untuk kode program lengkapnya seperti dibawah ini:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Ports;
using System.IO;
//using System.Threading.Tasks;

namespace SerialComm
{
    public partial class Form1 : Form
    {
        int idBtnKoneksi;
        DateTime tN;
        int idTglJam;

        String detik = "";
        String menit = "";
        String jam = "";
        String tanggal = "";
        String bulan = "";
        String tahun = "";
        String hari = "";

        public Form1()
        {
            InitializeComponent();

            idBtnKoneksi = 0;
            idTglJam = 0;
        }

        private void label5_Click(object sender, EventArgs e)
        {

        }

        private void btnKirimJam_Click(object sender, EventArgs e)
        {

        }

        //Cek port com yang tersedia / available / online di komputer, kemudian tampilkan di Combo box Port
        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                //Cek Port Com yang tersedia 
                cmbPort.Items.Clear();
                foreach (string s in SerialPort.GetPortNames())
                {
                    cmbPort.Items.Add(s);
                }

                if (cmbPort.Items.Count > 0)
                {
                    cmbPort.SelectedIndex = 0;
                }
                cmbDataBits.SelectedIndex = 3;
                cmbStopBits.SelectedIndex = 1;
                cmbParity.SelectedIndex = 0;
                cmbHandshake.SelectedIndex = 0;

                //Jalankan timer
                timer1.Interval = 500;
                timer1.Start();

                lblTanggal.Text = "";
                lblJam.Text = "";
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error:\n" + ex);
            }
        }

        public void tampilWaktu()
        {
            tN = DateTime.Now;

            if (tN.Second < 10)
            {
                detik = "0" + tN.Second.ToString();
            }
            else
            {
                detik = tN.Second.ToString();
            }

            if (tN.Minute < 10)
            {
                menit = "0" + tN.Minute.ToString();
            }
            else
            {
                menit = tN.Minute.ToString();
            }

            if (tN.Hour < 10)
            {
                jam = "0" + tN.Hour.ToString();
            }
            else
            {
                jam = tN.Hour.ToString();
            }

            if (tN.Day < 10)
            {
                tanggal = "0" + tN.Day.ToString();
            }
            else
            {
                tanggal = tN.Day.ToString();
            }

            if (tN.Month < 10)
            {
                bulan = "0" + tN.Month.ToString();
            }
            else
            {
                bulan = tN.Month.ToString();
            }

            if (tN.Year < 10)
            {
                //tahun = "0" + tN.Year.ToString();
            }
            else
            {
                tahun = tN.Year.ToString();
            }

            switch ((int)tN.DayOfWeek)
            {
                case 1:
                    hari = "Senin";
                    break;
                case 2:
                    hari = "Selasa";
                    break;
                case 3:
                    hari = "Rabu";
                    break;
                case 4:
                    hari = "Kamis";
                    break;
                case 5:
                    hari = "Jum'at";
                    break;
                case 6:
                    hari = "Sabtu";
                    break;
                case 7:
                    hari = "Minggu";
                    break;
                default:
                    break;
            }

            lblJam.Text = jam + ":" + menit + ":" + detik;
            //lblTanggal.Text = tN.DayOfWeek.ToString() + ", " + tanggal + "-" + bulan + "-" + tahun;
            lblTanggal.Text = hari + ", " + tanggal + "-" + bulan + "-" + tahun;
        }

        private void btnKoneksi_Click(object sender, EventArgs e)
        {
            try 
            {
                if (idBtnKoneksi % 2 == 0)
                {
                    if (cmbPort.Text != "")
                    {
                        serialPort1.PortName = cmbPort.Text;
                        serialPort1.BaudRate = int.Parse(cmbBaudRate.Text);
                        serialPort1.DataBits = int.Parse(cmbDataBits.Text);
                        serialPort1.StopBits = (StopBits)Enum.Parse(typeof(StopBits), cmbStopBits.Text);
                        serialPort1.Parity = (Parity)Enum.Parse(typeof(Parity), cmbParity.Text);
                        serialPort1.Handshake = (Handshake)Enum.Parse(typeof(Handshake), cmbHandshake.Text);

                        serialPort1.Open();
                        //tControl.SelectedIndex = 0;
                    }
                    else
                    {
                        MessageBox.Show(this, "Tidak ada Com port yang dipilih", "Com port tidak tersedia", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }

                    if (serialPort1.IsOpen)
                    {
                        toolStripStatusLabel1.Text = "Koneksi serial terhubung : " + serialPort1.PortName;
                        cmbPort.Enabled = false;
                        cmbBaudRate.Enabled = false;
                        cmbDataBits.Enabled = false;
                        cmbStopBits.Enabled = false;
                        cmbParity.Enabled = false;
                        cmbHandshake.Enabled = false;
                        btnKoneksi.Text = "Putuskan";
                        
                        idBtnKoneksi++;
                    }
                }
                else
                {
                    serialPort1.Close();
                    cmbPort.Enabled = true;
                    cmbBaudRate.Enabled = true;
                    cmbDataBits.Enabled = true;
                    cmbStopBits.Enabled = true;
                    cmbParity.Enabled = true;
                    cmbHandshake.Enabled = true;
                    btnKoneksi.Text = "Hubungkan";
                    toolStripStatusLabel1.Text = "Koneksi serial terputus.";
                    idBtnKoneksi++;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error:\n" + ex);
            }
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            try
            {
                if (idTglJam % 2 == 0) //Panggil fungsi tampilWaktu() setiap 1 detik
                {
                    tampilWaktu();
                }
                else
                {
                    idTglJam = 0;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message.ToString(), "Exception !", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnKirimData_Click(object sender, EventArgs e)
        {
            try
            {
                if(serialPort1.IsOpen)
                {
                    if (textBoxDataKirim.Text == "")
                    {
                        MessageBox.Show(this, "Ketikkan terlebih dahulu data yang akan dikirim", "Data Kosong!!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    else
                    {
                        serialPort1.Write(textBoxDataKirim.Text);
                        textBoxDataKirim.Text = "";
                    }
                }
                else
                {
                    MessageBox.Show(this, "Koneksi serial belum tersambung !", "Koneksi Serial", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message.ToString(), "Exception !", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                //MessageBox.Show("Ada data serial diterima!!");
                string data = serialPort1.ReadExisting();
                richTextBoxDataTerima.Invoke(new EventHandler(delegate { richTextBoxDataTerima.AppendText(data); }));
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message.ToString(), "Exception !", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            try
            {
                serialPort1.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message.ToString(), "Exception !", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnClearRTBox_Click(object sender, EventArgs e)
        {
            try
            {
                richTextBoxDataTerima.Clear();
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message.ToString(), "Exception !", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnSimpan_Click(object sender, EventArgs e)
        {
            try
            {
                String path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

                //SaveFileDialog saveFileDialog1 = new SaveFileDialog();
                saveFileDialog1.InitialDirectory = path;
                saveFileDialog1.Title = "Save text Files";
                saveFileDialog1.CheckFileExists = false;
                saveFileDialog1.CheckPathExists = true;
                saveFileDialog1.DefaultExt = "txt";
                saveFileDialog1.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
                saveFileDialog1.FilterIndex = 1;
                saveFileDialog1.RestoreDirectory = true;

                if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    if (!File.Exists(saveFileDialog1.FileName))
                    {
                        File.Create(saveFileDialog1.FileName).Dispose();
                        //richTextBoxDataTerima.Text = "File created!";
                        //richTextBoxDataTerima.AppendText(Environment.NewLine + saveFileDialog1.FileName);
                        //richTextBoxDataTerima.Text += Environment.NewLine + "My new line.";
                        File.WriteAllText(saveFileDialog1.FileName, richTextBoxDataTerima.Text);
                        //File.AppendAllText(saveFileDialog1.FileName, "\n\n" + richTextBoxDataTerima.Text);
                    }
                    else
                    {
                        //richTextBoxDataTerima.Text = "File exist.";
                        //richTextBoxDataTerima.AppendText(Environment.NewLine + saveFileDialog1.FileName);
                        File.WriteAllText(saveFileDialog1.FileName, richTextBoxDataTerima.Text);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message.ToString(), "Exception !", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnKoneksi2_Click(object sender, EventArgs e)
        {
            btnKoneksi_Click(null, null);
        }
    }
}

Tidak ada komentar:

Posting Komentar