Master Modbus RTU untuk memberi perintah Slave Modbus RTU khususnya untuk function Code 03 , yaitu untuk membaca data register slave RTU microcontroller pada artikel sebelumya.
Tampilan Menu Utama
Kode program dengan C#:
//sebelumnya anda drag and drop komponen serial comm ke form dan ganti namanya menjadi serialPort1.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace SimpleSerial
{
public partial class Form1 : Form
{
string RxString_Respon_dari_slave;
private void buttonStart_Click(object sender, EventArgs e)
{
serialPort1.PortName = "COM1";
serialPort1.BaudRate = 9600;
serialPort1.Open();
if (serialPort1.IsOpen)
{
buttonStart.Enabled = false;
buttonStop.Enabled = true;
textBox1.ReadOnly = false;
}
}
private void buttonStop_Click(object sender, EventArgs e)
{
if (serialPort1.IsOpen)
{
serialPort1.Close();
buttonStart.Enabled = true;
buttonStop.Enabled = false;
textBox1.ReadOnly = true;
}
}
private void button2_Click(object sender, EventArgs e)
{
byte[] CRC = new byte[2];
byte[] message = new byte[8];
ushort start = Convert.ToUInt16(textAlamatAwal.Text);
ushort reg_qty = Convert.ToUInt16(textJumlahRegister.Text);
// jika port belum di open , keluar
if (!serialPort1.IsOpen) return;
//Clear in/out buffers:
serialPort1.DiscardOutBuffer();
serialPort1.DiscardInBuffer();
message[0] = Convert.ToByte(txtalamat.Text);
message[1] = Convert.ToByte(textFunctionCode.Text);
message[2] = (byte)(start >> 8);
message[3] = (byte)start;
message[4] = (byte)(reg_qty >> 8);
message[5] = (byte)reg_qty;
HitungCRC(message, ref CRC);
message[message.Length-2] = CRC[0];
message[message.Length-1] = CRC[1];
//tampilkan hasil CRC ke textbox
textCRC.Text = CRC[1].ToString() + " " + CRC[0].ToString();
textCRCHigh.Text = CRC[1].ToString();
textCRCLow.Text = CRC[0].ToString();
//kirim data di buffer message ke serial port
serialPort1.Write(message, 0, message.Length);
}
//tampilkan data respon dari slave
private void DisplayText(object sender, EventArgs e)
{
textBox1.AppendText(RxString_Respon_dari_slave);
}
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
RxString_Respon_dari_slave = serialPort1.ReadExisting();
this.Invoke(new EventHandler(DisplayText));
}
private void HitungCRC(byte[] message, ref byte[] CRC)
{
ushort CRCFull = 0xFFFF;
byte CRCHigh = 0xFF, CRCLow = 0xFF;
char CRCLSB;
for (int i = 0; i < (message.Length) - 2; i++)
{
CRCFull = (ushort)(CRCFull ^ message[i]);
for (int j = 0; j < 8; j++)
{
CRCLSB = (char)(CRCFull & 0x0001);
CRCFull = (ushort)((CRCFull >> 1) & 0x7FFF);
if (CRCLSB == 1)
CRCFull = (ushort)(CRCFull ^ 0xA001);
}
}
CRC[1] = CRCHigh = (byte)((CRCFull >> 8) & 0xFF);
CRC[0] = CRCLow = (byte)(CRCFull & 0xFF);
}
0 komentar:
Posting Komentar