SpSetup 类 与Globalspace类
public partial class SpSetup : Form
{
#region 定义变量
/// <summary>
/// 发送报文
/// </summary>
public byte[] sendData = new byte[8];
#endregion
#region 构造读取状态报文
/// <summary>
/// 构造读取状态报文
/// </summary>
public void GetSendData()
{
byte[] data = new byte[6];
byte[] Address = Globalspace.intToHexByte(Globalspace.startAddress);
byte[] nubmer = Globalspace.intToHexByte(Globalspace.registerNumber);
data[0] = Globalspace.ID; //从机地址
data[1] = Convert.ToByte(Globalspace.modbusPointType.readHoldingRegister); //功能号 - 读取保持寄存器
data[2] = Address[0]; //数据地址
data[3] = Address[1]; //数据地址
data[4] = nubmer[0]; //数据
data[5] = nubmer[1]; //数据
for (int i = 0; i < 6; i++)
{
sendData[i] = data[i]; //报文是用串口发送的
}
Byte[] CRC = new Byte[2];
CRC = Globalspace.CRC_16(data); //进行CRC效验
sendData[6] = CRC[0];
sendData[7] = CRC[1];
}
#endregion
}
class Globalspace
{
#region 定义变量
/// <summary>
/// 定义串口
/// </summary>
public static SerialPort sp = new SerialPort();
/// <summary>
/// Modbus 通讯地址
/// </summary>
public static byte ID = 2;
/// <summary>
/// Modbus 功通讯能码
/// </summary>
public enum modbusPointType
{
readCoilStatus = 01, //读取线圈状态
readInputStatus = 02, //读取输入状态
readHoldingRegister = 03, //读取保持寄存器
readInputRegister = 04, //读取输入寄存器
writeSingleCoil = 05, //强置单线圈
writeSingleRegister = 06, //保持寄存器写入(仅一点)
writeMultipleCoil = 15, //强置多线圈
writeMultipleRegister = 16,//预置多寄存器
};
/// <summary>
/// 起始地址
/// </summary>
public static int startAddress = 99;//读D100地址内容
/// <summary>
/// 读取数量
/// </summary>
public static int registerNumber = 1;//读一个
/// <summary>
/// 读写标志位 true —读;false —写。
/// </summary>
public static bool readORwrite = true;
/// <summary>
/// 读完成标志
/// </summary>
public static bool readDone = true; //读取数据完成后,清零
/// <summary>
/// 写完成标志
/// </summary>
public static bool writeDone = true;//写入数据完成后,清零
/// <summary>
/// 创建发送表
/// </summary>
public static ArrayList sendList = new ArrayList();//创建发送表
/// <summary>
/// 创建接收表
/// </summary>
public static ArrayList receivedList = new ArrayList();//创建接收表
/// <summary>
/// 读数据定时器
/// </summary>
public static System.Timers.Timer readTimer = new System.Timers.Timer(2000);
/// <summary>
/// 写数据定时器
/// </summary>