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();
}));
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?