基本信息
源码名称:好用的moudbus使用类 读写
源码大小:3.17KB
文件格式:.rar
开发语言:C#
更新时间:2021-08-14
   友情提示:(无需注册或充值,赞助后即可获取资源下载链接)

     嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):78630559

本次赞助数额为: 2 元 
   源码介绍

打开关闭串口方法
/// 打开串口方法【9600 N 8 1】OpenMyComm
关闭串口方法
ClosePort()

串口接受数据事件
///
///
///
void MyCom_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
while (MyCom.BytesToRead > 0)
{
mReceiveByte = (byte)MyCom.ReadByte();
bData[mReceiveByteCount] = mReceiveByte;
mReceiveByteCount = 1;
if (mReceiveByteCount >= 1024)
{
mReceiveByteCount = 0;
//清除输入缓存区
MyCom.DiscardInBuffer();
return;
}
}
读取保持型寄存器 功能码0x03
预置单字保持型寄存器 功能码0x06

预置双字保持型寄存器 功能码0x10

读取输出线圈 功能码0x01

读取输入线圈 功能码0x02

强制单线圈 功能码0x05

读取保持型寄存器 功能码0x03

public bool PreSetKeepReg(int iDevAdd, int iAddress, int SetValue)
{
byte[] ResByte;
byte[] SendCommand = new byte[8];
CurrentAddr = iDevAdd;
//第一步:拼接报文
SendCommand[0] = (byte)iDevAdd;
SendCommand[1] = 0x06;
SendCommand[2] = (byte)((iAddress - iAddress % 256) / 256);
SendCommand[3] = (byte)(iAddress % 256);
SendCommand[4] = (byte)((SetValue - SetValue % 256) / 256);
SendCommand[5] = (byte)(SetValue % 256);
Crc16(SendCommand, 6);
SendCommand[6] = ucCRCLo;
SendCommand[7] = ucCRCHi;
try
{
//第二步:发送报文
MyCom.Write(SendCommand, 0, 8);
}
catch (Exception)
{
return false;
}
mReceiveByteCount = 0;
Thread.Sleep(100);
//第三步:解析报文
ResByte = HexStringToByteArray(this.strUpData, 0, 0);
return ByteArrayEquals(SendCommand, ResByte);
}


//定义串口类对象
private SerialPort MyCom;
//定义CRC校验高低位
private byte ucCRCHi = 0xFF;
private byte ucCRCLo = 0xFF;
//定义接收字节数组
byte[] bData = new byte[1024];
byte mReceiveByte;
int mReceiveByteCount = 0;
//定义设备地址
int CurrentAddr;
int iMWordLen;
int iMBitLen;
//定义返回报文
string strUpData;
public Modbus()
{
MyCom = new SerialPort();
}