Bläddra i källkod

写多个寄存器

dev1
永攀 张 2 veckor sedan
förälder
incheckning
bf15605454
4 ändrade filer med 92 tillägg och 14 borttagningar
  1. +3
    -0
      ModbusDemo/Device/IModbusRTU.cs
  2. +58
    -3
      ModbusDemo/Device/ModbusRTU.cs
  3. +12
    -6
      ModbusDemo/VIew/CoilUC.xaml
  4. +19
    -5
      ModbusDemo/VIewModel/RegisterUCViewModel.cs

+ 3
- 0
ModbusDemo/Device/IModbusRTU.cs Visa fil

@@ -15,5 +15,8 @@ namespace ModbusDemo.Device


public ushort[] ReadRegisters(byte slaveAddress, ushort startAddress, ushort numberOfPoints); public ushort[] ReadRegisters(byte slaveAddress, ushort startAddress, ushort numberOfPoints);



public void WriteRegisters(byte slaveAddress, ushort startAddress, ushort[] data);

} }
} }

+ 58
- 3
ModbusDemo/Device/ModbusRTU.cs Visa fil

@@ -58,7 +58,7 @@ namespace ModbusDemo.Device
Thread.Sleep(300); Thread.Sleep(300);
byte[] response = new byte[_serialPort.BytesToRead]; byte[] response = new byte[_serialPort.BytesToRead];
_serialPort.Read(response, 0, _serialPort.BytesToRead); _serialPort.Read(response, 0, _serialPort.BytesToRead);
return ParseCoilresponse(response,numberOfPoints);
return ParseCoilresponse(response, numberOfPoints);
} }




@@ -170,12 +170,12 @@ namespace ModbusDemo.Device
if (!CRCUitl.ValidateCRC(response)) if (!CRCUitl.ValidateCRC(response))
{ {
MessageBox.Show("0x14:CRC校验错误"); MessageBox.Show("0x14:CRC校验错误");
} }
} }




} }


public ushort[] ReadRegisters(byte slaveAddress, ushort startAddress, ushort numberOfPoints) public ushort[] ReadRegisters(byte slaveAddress, ushort startAddress, ushort numberOfPoints)
@@ -238,5 +238,60 @@ namespace ModbusDemo.Device


return registers; return registers;
} }

public void WriteRegisters(byte slaveAddress, ushort startAddress, ushort[] data)
{
List<byte> sendByteList = new List<byte>();
//设置从站地址
sendByteList.Add(slaveAddress);
//设置功能码
sendByteList.Add(0x10);
//设置起始地址的高位和低位
sendByteList.Add(BitConverter.GetBytes(startAddress)[1]);
sendByteList.Add(BitConverter.GetBytes(startAddress)[0]);
//设置写入几个线圈
sendByteList.Add(BitConverter.GetBytes(data.Length)[1]);
sendByteList.Add(BitConverter.GetBytes(data.Length)[0]);

// 计算字节数
int byteCount = (data.Length + 7) / 8;
sendByteList.Add((byte)byteCount);

foreach (ushort value in data)
{
byte[] valueBytes = BitConverter.GetBytes(value);
// 大端序:高字节在前,低字节在后
sendByteList.Add(valueBytes[1]);
sendByteList.Add(valueBytes[0]);
}

//获取CRC校验码
byte[] getCRC = sendByteList.ToArray();
byte[] resultCRC = CRCUitl.CalculateCRC(getCRC, getCRC.Length);
sendByteList.Add(resultCRC[0]);
sendByteList.Add(resultCRC[1]);


byte[] sendByte = sendByteList.ToArray();
if (_serialPort.IsOpen)
{
// 清空接收缓冲区(避免残留数据干扰)
_serialPort.DiscardInBuffer();

_serialPort.Write(sendByte, 0, sendByte.Length);
Thread.Sleep(300);
byte[] response = new byte[_serialPort.BytesToRead];
_serialPort.Read(response, 0, _serialPort.BytesToRead);

//判断发送回来的数据是否正确
CheckData.CheckResponse(response);

if (!CRCUitl.ValidateCRC(response))
{
MessageBox.Show("0x14:CRC校验错误");

}
}
}
} }
} }

+ 12
- 6
ModbusDemo/VIew/CoilUC.xaml Visa fil

@@ -15,8 +15,8 @@
mc:Ignorable="d"> mc:Ignorable="d">
<UserControl.Resources> <UserControl.Resources>
<Style TargetType="TextBox"> <Style TargetType="TextBox">
<Setter Property="Margin" Value="0,5"/>
<Setter Property="FontSize" Value="14"/>
<Setter Property="Margin" Value="0,5" />
<Setter Property="FontSize" Value="14" />
</Style> </Style>
</UserControl.Resources> </UserControl.Resources>
<Grid> <Grid>
@@ -52,8 +52,10 @@
</ColumnDefinition> </ColumnDefinition>
</Grid.ColumnDefinitions> </Grid.ColumnDefinitions>
<Grid.RowDefinitions> <Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition Height="60"></RowDefinition>
<RowDefinition>
</RowDefinition>
<RowDefinition Height="60">
</RowDefinition>
</Grid.RowDefinitions> </Grid.RowDefinitions>
<StackPanel HorizontalAlignment="Center" Orientation="Vertical"> <StackPanel HorizontalAlignment="Center" Orientation="Vertical">
<TextBlock Margin="20" Text="从站地址"> <TextBlock Margin="20" Text="从站地址">
@@ -78,9 +80,9 @@


<StackPanel Grid.Row="2" Grid.ColumnSpan="4" HorizontalAlignment="Center" Orientation="Horizontal"> <StackPanel Grid.Row="2" Grid.ColumnSpan="4" HorizontalAlignment="Center" Orientation="Horizontal">


<TextBlock Text="读取结果:" Margin="0,20,0,0" FontWeight="Black"/>
<TextBlock Margin="0,20,0,0" Text="读取结果:" FontWeight="Black" />


<TextBox Margin="20,0,0,0" MinWidth="120" Text="{Binding ReadResult}" Style="{StaticResource MaterialDesignOutlinedTextBox}"/>
<TextBox MinWidth="120" Margin="20,0,0,0" Text="{Binding ReadResult}" Style="{StaticResource MaterialDesignOutlinedTextBox}" />
</StackPanel> </StackPanel>
<Button <Button
Grid.Column="4" Grid.Column="4"
@@ -145,5 +147,9 @@
Style="{StaticResource MaterialDesignRaisedDarkButton}"> Style="{StaticResource MaterialDesignRaisedDarkButton}">
</Button> </Button>
</Grid> </Grid>

<Grid Grid.Row="3">

</Grid>
</Grid> </Grid>
</UserControl> </UserControl>

+ 19
- 5
ModbusDemo/VIewModel/RegisterUCViewModel.cs Visa fil

@@ -176,14 +176,28 @@ namespace ModbusDemo.VIewModel
} }
private void WriteRegister() private void WriteRegister()
{ {
//去除字符串中的空格
WriteData = WriteData.Replace(" ", "");
//转换为布尔数组
bool[] data = WriteData.Select(m => m == '1').ToArray();
string[] parts = WriteData.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
// 3. 创建结果数组
ushort[] data = new ushort[parts.Length];

// 4. 遍历并转换每个部分
for (int i = 0; i < parts.Length; i++)
{
// 尝试解析为ushort
if (ushort.TryParse(parts[i], out ushort value))
{
data[i] = value;
}
else
{
// 处理解析失败的情况
throw new FormatException($"无法将 '{parts[i]}' 转换为 ushort 类型");
}
}


try try
{ {
_modbusRTU.WriteCoil(byte.Parse(WriteSlaveAddress),
_modbusRTU.WriteRegisters(byte.Parse(WriteSlaveAddress),
ushort.Parse(WriteStartAddress), ushort.Parse(WriteStartAddress),
data); data);
} }


Laddar…
Avbryt
Spara