简单C#代码实现modbus-rtu通讯发送数据
简单C#代码实现modbus-rtu通讯发送数据
实现效果
代码
闲言少叙,直接上代码:
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;
using System.IO.Ports;
namespace Simple_Rtu
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
SerialPort Sp1 = new SerialPort();
private void button1_Click(object sender, EventArgs e)
{
if (Sp1.IsOpen)
{
Sp1.Close();
}
Sp1.BaudRate = 9600;
Sp1.PortName = "com6";
Sp1.DataBits = 8;
Sp1.Parity = System.IO.Ports.Parity.None;
Sp1.StopBits = System.IO.Ports.StopBits.One;
Sp1.ReadTimeout = 2000;
Sp1.Open();
if (Sp1.IsOpen)
{
MessageBox.Show("success");
}
}
private void button2_Click(object sender, EventArgs e)
{
byte[] SendCommand = new byte[8];
SendCommand[0] = 0x01;
SendCommand[1] = 0x03;
SendCommand[2] = (byte)(10 / 256);
SendCommand[3] = (byte)(10 % 256);
SendCommand[4] = (byte)(10 / 256);
SendCommand[5] = (byte)(10 % 256);
byte[] crc16 = Crc16(SendCommand, 6);
SendCommand[6] = crc16[0];
SendCommand[7] = crc16[1];
Sp1.Write(SendCommand, 0, SendCommand.Length);
textBox1.Text = BitConverter.ToString(SendCommand);
}
private static readonly byte[] aucCRCHi = //crc高位表
{
0x00