嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):78630559
本次赞助数额为: 2 元微信扫码支付:2 元
请留下您的邮箱,我们将在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();
}