简单C#代码实现modbus-rtu通讯发送数据

本文提供了使用C#语言简单实现Modbus-RTU通讯的代码片段,专注于通过串口发送数据。
摘要由CSDN通过智能技术生成

简单C#代码实现modbus-rtu通讯发送数据

简单C#代码实现modbus-rtu通讯发送数据

实现效果

上面是发送界面,下面是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
  • 7
    点赞
  • 58
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值