NModbus4项目2——模拟量数据的读取与显示

PLC中常用的数据类型分别是:

1、布尔量

2、整数,16位,整数为有符号数,最高位为符号,1表示复数,0表示正数,范围:-32768~32767;

3、浮点数,32位,用来表示小数

 

 

 

由于NModbus4读取到寄存器的数据都是ushort类型,因此读数据时需要将转ushort换成整数或者浮点数,或者在写数据时需要将整数或浮点数转换成ushort数据类型。

这里使用thinger.DataConvertLib类库,先添加引用using thinger.DataConvertLib;

 

读数据: 

布尔量数据直接读取即可;

整数读取得到的是ushort,需要转换成short或Int16;

方法如下:

            //读取多个保持寄存器
ushort
[] data1 = master.ReadHoldingRegisters(1, 0, 8);
       short[] shorts = new short[data1.Length]; 
//第一种方法 //for (int i = 0; i < data1.Length; i++) //{ // byte[] bytes = ByteArrayLib.GetByteArrayFromUShort(data1[i]); // shorts[i] = ShortLib.GetShortFromByteArray(bytes); //} //第二种方法 for (int i = 0; i < shorts.Length; i++) { shorts[i] = (Int16)Convert.ToUInt16(data1[i]); } this.Invoke(new Action(() => { this.tbInt1.Text = shorts[0].ToString(); this.tbInt2.Text = shorts[1].ToString(); this.tbInt3.Text = shorts[2].ToString(); this.tbInt4.Text = shorts[3].ToString(); }));

读浮点数:

            //2、读小数
            ushort[] data2 = master.ReadHoldingRegisters(1, 100, 8);
            float[] floats = new float[data2.Length / 2];
            floats = FloatLib.GetFloatArrayFromByteArray(ByteArrayLib.GetByteArrayFromUShortArray(data2), DataFormat.CDAB);

            this.Invoke(new Action(() =>
            {
                this.tbReal1.Text = floats[0].ToString();
                this.tbReal2.Text = floats[1].ToString();
                this.tbReal3.Text = floats[2].ToString();
                this.tbReal4.Text = floats[3].ToString();
            }));            

 

写数据:

整数写入:

short.TryParse(this.tbInt6.Text.Trim(), out short i16);
master.WriteSingleRegister(1, 5, (ushort)i16);

写入浮点数

float.TryParse(tbReal5.Text.Trim(), out float f);
byte[] bs = BitConverter.GetBytes(f);
ushort[] usArray = UShortLib.GetUShortArrayFromByteArray(bs, DataFormat.DCBA);
master.WriteMultipleRegisters(1, 108, usArray);

 

 

 

 

//读数据
//1、读整数
ushort[] data1 = master.ReadHoldingRegisters(1, 0, 8);
short[] shorts = new short[data1.Length];
for (int i = 0; i < data1.Length; i++)
{
byte[] bytes = ByteArrayLib.GetByteArrayFromUShort(data1[i]);
shorts[i] = ShortLib.GetShortFromByteArray(bytes);
}
this.Invoke(new Action(() =>
{

this.tbInt1.Text = shorts[0].ToString();
this.tbInt2.Text = shorts[1].ToString();
this.tbInt3.Text = shorts[2].ToString();
this.tbInt4.Text = shorts[3].ToString();
}));

//2、读小数
ushort[] data2 = master.ReadHoldingRegisters(1, 100, 8);
float[] floats = new float[data2.Length / 2];
floats = FloatLib.GetFloatArrayFromByteArray(ByteArrayLib.GetByteArrayFromUShortArray(data2),DataFormat.CDAB);
this.Invoke(new Action(() =>
{
this.tbReal1.Text = floats[0].ToString();
this.tbReal2.Text = floats[1].ToString();
this.tbReal3.Text = floats[2].ToString();
this.tbReal4.Text = floats[3].ToString();
}));

 

posted on 2022-11-18 16:13  hanzq_go  阅读(1420)  评论(0编辑  收藏  举报

导航