添加项目文件。

This commit is contained in:
ly 2025-03-05 11:21:04 +08:00
parent ccc3bc0325
commit c791e32d9c
14 changed files with 1140 additions and 0 deletions

25
ControlcBoardsTest.sln Normal file
View File

@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.11.35222.181
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ControlcBoardsTest", "ControlcBoardsTest\ControlcBoardsTest.csproj", "{6FD3F202-2D0F-4501-8F7C-3DA7384B4B95}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{6FD3F202-2D0F-4501-8F7C-3DA7384B4B95}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{6FD3F202-2D0F-4501-8F7C-3DA7384B4B95}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6FD3F202-2D0F-4501-8F7C-3DA7384B4B95}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6FD3F202-2D0F-4501-8F7C-3DA7384B4B95}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {EAECA0FF-43E9-43D2-8868-02CBD267158F}
EndGlobalSection
EndGlobal

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5"/>
</startup>
</configuration>

View File

@ -0,0 +1,9 @@
<Application x:Class="ControlcBoardsTest.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:ControlcBoardsTest"
StartupUri="MainWindow.xaml">
<Application.Resources>
</Application.Resources>
</Application>

View File

@ -0,0 +1,17 @@
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
namespace ControlcBoardsTest
{
/// <summary>
/// App.xaml 的交互逻辑
/// </summary>
public partial class App : Application
{
}
}

View File

@ -0,0 +1,110 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{6FD3F202-2D0F-4501-8F7C-3DA7384B4B95}</ProjectGuid>
<OutputType>WinExe</OutputType>
<RootNamespace>ControlcBoardsTest</RootNamespace>
<AssemblyName>ControlcBoardsTest</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<WarningLevel>4</WarningLevel>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Deterministic>true</Deterministic>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="HslCommunication, Version=12.2.0.0, Culture=neutral, PublicKeyToken=3d72ad3b6b5ec0e3, processorArchitecture=MSIL">
<HintPath>..\packages\HslCommunication.12.2.0\lib\net35\HslCommunication.dll</HintPath>
</Reference>
<Reference Include="Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\packages\Newtonsoft.Json.13.0.1\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="NModbus4, Version=2.1.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\NModbus4.2.1.0\lib\net40\NModbus4.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xaml">
<RequiredTargetFramework>4.0</RequiredTargetFramework>
</Reference>
<Reference Include="WindowsBase" />
<Reference Include="PresentationCore" />
<Reference Include="PresentationFramework" />
</ItemGroup>
<ItemGroup>
<ApplicationDefinition Include="App.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</ApplicationDefinition>
<Page Include="MainWindow.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Compile Include="App.xaml.cs">
<DependentUpon>App.xaml</DependentUpon>
<SubType>Code</SubType>
</Compile>
<Compile Include="ModbusHelper.cs" />
<Compile Include="MainWindow.xaml.cs">
<DependentUpon>MainWindow.xaml</DependentUpon>
<SubType>Code</SubType>
</Compile>
</ItemGroup>
<ItemGroup>
<Compile Include="Properties\AssemblyInfo.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<Compile Include="Properties\Settings.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
<None Include="packages.config" />
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
</None>
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

View File

@ -0,0 +1,94 @@
<Window x:Class="ControlcBoardsTest.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:ControlcBoardsTest"
mc:Ignorable="d"
Title="MainWindow" Height="450" Width="1050">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="0.2*"></RowDefinition>
<RowDefinition Height="0.2*"></RowDefinition>
<RowDefinition Height="0.2*"></RowDefinition>
<RowDefinition Height="0.2*"></RowDefinition>
</Grid.RowDefinitions>
<Grid>
<StackPanel Orientation="Horizontal">
<TextBlock Text="串口号" Margin="5,0,10,0" VerticalAlignment="Center"></TextBlock>
<ComboBox Width="80" VerticalAlignment="Center" Name="com_port"></ComboBox>
<TextBlock Margin="20,0,10,0" Text="波特率" VerticalAlignment="Center"></TextBlock>
<TextBox Text="9600" VerticalAlignment="Center" Width=" 80" Name="txt_baudRate"></TextBox>
<TextBlock Margin="20,0,10,0" Text="数据位" VerticalAlignment="Center"></TextBlock>
<TextBox Text="8" VerticalAlignment="Center" Width=" 60" Name="txt_sataBits"></TextBox>
<TextBlock Margin="20,0,10,0" Text="停止位" VerticalAlignment="Center"></TextBlock>
<TextBox Text="1" VerticalAlignment="Center" Width=" 60" Name="txt_stopBits"></TextBox>
<TextBlock Margin="20,0,10,0" Text="站号" VerticalAlignment="Center"></TextBlock>
<TextBox Text="2" VerticalAlignment="Center" Width=" 60" Name="txt_stationNo"></TextBox>
<Button Content="连接" Margin="20,0,10,0" Width="80" VerticalAlignment="Center" Name="btn_conn" Click="connButton_Click"></Button>
<Button Content="循环测试开始" Margin="20,0,10,0" Name='btn_always' Width="80" VerticalAlignment="Center" Click="Button_Click_13"></Button>
<Button Content="正反转测试开始" Margin="20,0,10,0" Name='btn_FrontBack' Width="100" VerticalAlignment="Center" Click="btn_FrontBack_Click"></Button>
</StackPanel>
</Grid>
<WrapPanel Grid.Row="1" Name="warp_channel">
<Button Content="通道1输出" Tag="0" Width='80' Click="Button_Click" Margin="5"></Button>
<Button Content="通道2输出" Tag="1" Width='80' Click="Button_Click" Margin="5"></Button>
<Button Content="通道3输出" Tag="2" Width='80' Click="Button_Click" Margin="5"></Button>
<Button Content="通道4输出" Tag="3" Width='80' Click="Button_Click" Margin="5"></Button>
<Button Content="通道5输出" Tag="4" Width='80' Click="Button_Click" Margin="5"></Button>
<Button Content="通道6输出" Tag="5" Width='80' Click="Button_Click" Margin="5"></Button>
<Button Content="通道7输出" Tag="6" Width='80' Click="Button_Click" Margin="5"></Button>
<Button Content="通道8输出" Tag="7" Width='80' Click="Button_Click" Margin="5"></Button>
<Button Content="通道9输出" Tag="8" Width='80' Click="Button_Click" Margin="5"></Button>
<Button Content="通道10输出" Tag="9" Width='80' Click="Button_Click" Margin="5"></Button>
<Button Content="通道11输出" Tag="10" Width='80' Click="Button_Click" Margin="5"></Button>
<Button Content="通道12输出" Tag="11" Width='80' Click="Button_Click" Margin="5"></Button>
<Button Content="通道13输出" Tag="12" Width='80' Click="Button_Click" Margin="5"></Button>
<Button Content="通道14输出" Tag="13" Width='80' Click="Button_Click" Margin="5"></Button>
<Button Content="通道15输出" Tag="14" Width='80' Click="Button_Click" Margin="5"></Button>
<Button Content="通道16输出" Tag="15" Width='80' Click="Button_Click" Margin="5"></Button>
</WrapPanel>
<WrapPanel Grid.Row="2" Name="warp_ElectricMotor">
<Button Content="电机1正转" Tag="0" Width='80' Name="btn_ElectricMotor1Front" Click="Button_Click_1" Margin="5"></Button>
<Button Content="电机1反转" Tag="1" Width='80' Name="btn_ElectricMotor1Back" Click="Button_Click_2" Margin="5"></Button>
<Button Content="电机2正转" Tag="0" Width='80' Name="btn_ElectricMotor2Front" Click="Button_Click_3" Margin="5"></Button>
<Button Content="电机2反转" Tag="1" Width='80' Name="btn_ElectricMotor2Back" Click="Button_Click_4" Margin="5"></Button>
<Button Content="电机3正转" Tag="0" Width='80' Name="btn_ElectricMotor3Front" Click="Button_Click_5" Margin="5"></Button>
<Button Content="电机3反转" Tag="1" Width='80' Name="btn_ElectricMotor3Back" Click="Button_Click_6" Margin="5"></Button>
<Button Content="电机4正转" Tag="0" Width='80' Name="btn_ElectricMotor4Front" Click="Button_Click_7" Margin="5"></Button>
<Button Content="电机4反转" Tag="1" Width='80' Name="btn_ElectricMotor4Back" Click="Button_Click_8" Margin="5"></Button>
</WrapPanel>
<WrapPanel Grid.Row="3">
<StackPanel Orientation="Horizontal" VerticalAlignment="Center">
<TextBlock Text="通道1速度" VerticalAlignment="Center" Margin="5"></TextBlock>
<TextBox Width="60" Name="txt_channel1Speed" Margin="5"></TextBox>
<Button Content="下发" Margin="5" Width="60" Click="Button_Click_9"></Button>
</StackPanel>
<StackPanel Orientation="Horizontal" VerticalAlignment="Center">
<TextBlock Text="通道2速度" VerticalAlignment="Center" Margin="5"></TextBlock>
<TextBox Width="60" Name="txt_channel2Speed" Margin="5"></TextBox>
<Button Content="下发" Margin="5" Width="60" Click="Button_Click_10"></Button>
</StackPanel>
<StackPanel Orientation="Horizontal" VerticalAlignment="Center">
<TextBlock Text="通道3速度" VerticalAlignment="Center" Margin="5"></TextBlock>
<TextBox Width="60" Name="txt_channel3Speed" Margin="5"></TextBox>
<Button Content="下发" Margin="5" Width="60" Click="Button_Click_11"></Button>
</StackPanel>
<StackPanel Orientation="Horizontal" VerticalAlignment="Center">
<TextBlock Text="通道4速度" VerticalAlignment="Center" Margin="5"></TextBlock>
<TextBox Width="60" Name="txt_channel4Speed" Margin="5"></TextBox>
<Button Content="下发" Margin="5" Width="60" Click="Button_Click_12"></Button>
</StackPanel>
</WrapPanel>
</Grid>
</Window>

View File

@ -0,0 +1,524 @@
using Modbus.Device;
using System;
using System.IO.Ports;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
namespace ControlcBoardsTest
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.Loaded += MainWindow_Loaded;
this.Closing += MainWindow_Closing;
}
private void MainWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
//停止通道
for (int i = 0; i < 24; i++)
{
ModbusHelper.WriteSingleCoil(stationNo, (ushort)i, false);
}
ModbusHelper.WriteSingleCoil(stationNo, 16, false);
ModbusHelper.WriteSingleCoil(stationNo, 18, false);
ModbusHelper.WriteSingleCoil(stationNo, 20, false);
ModbusHelper.WriteSingleCoil(stationNo, 22, false);
ModbusHelper.WriteSingleCoil(stationNo, 17, false);
ModbusHelper.WriteSingleCoil(stationNo, 19, false);
ModbusHelper.WriteSingleCoil(stationNo, 21, false);
ModbusHelper.WriteSingleCoil(stationNo, 23, false);
ModbusHelper.master.Close();
}
private void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
foreach (var item in SerialPort.GetPortNames())
{
com_port.Items.Add(item);
if (com_port.Items.Count > 0)
com_port.SelectedIndex = 0;
}
}
private byte stationNo;
private void connButton_Click(object sender, RoutedEventArgs e)
{
//打开串口
if (!ModbusHelper.master.IsOpen())
{
//创建ModbusRTU主站实例
ModbusHelper.master.SerialPortInni(serialPort =>
{
//设定串口参数
serialPort.PortName = com_port.SelectedItem.ToString();
serialPort.BaudRate = Convert.ToInt32(txt_baudRate.Text.ToString());
serialPort.Parity = 0;
serialPort.DataBits = Convert.ToInt32(txt_sataBits.Text.ToString());
serialPort.StopBits = ModbusHelper.GetSelectedStopBits(Convert.ToDouble(txt_stopBits.Text.ToString()));
stationNo = Convert.ToByte(txt_stationNo.Text);
});
ModbusHelper.master.Open();
if (ModbusHelper.master.IsOpen())
{
btn_conn.Content = "断开";
for (int i = 0; i < 24; i++)
{
ModbusHelper.WriteSingleCoil(stationNo, (ushort)i, false);
Thread.Sleep(100);
}
var CoilsRes = ModbusHelper.ReadCoils(stationNo, 0, 24);
foreach (var item in warp_channel.Children)
{
if (item is Button)
{
var c = (Button)item;
c.Background = new SolidColorBrush(CoilsRes[Convert.ToUInt16(c.Tag)] ? Colors.Green : Colors.Red);
}
}
btn_ElectricMotor1Front.Background = new SolidColorBrush(CoilsRes[Convert.ToUInt16(16)] ? Colors.Green : Colors.Red);
btn_ElectricMotor1Back.Background = new SolidColorBrush(CoilsRes[Convert.ToUInt16(17)] ? Colors.Green : Colors.Red);
btn_ElectricMotor2Front.Background = new SolidColorBrush(CoilsRes[Convert.ToUInt16(18)] ? Colors.Green : Colors.Red);
btn_ElectricMotor2Back.Background = new SolidColorBrush(CoilsRes[Convert.ToUInt16(19)] ? Colors.Green : Colors.Red);
btn_ElectricMotor3Front.Background = new SolidColorBrush(CoilsRes[Convert.ToUInt16(20)] ? Colors.Green : Colors.Red);
btn_ElectricMotor3Back.Background = new SolidColorBrush(CoilsRes[Convert.ToUInt16(21)] ? Colors.Green : Colors.Red);
btn_ElectricMotor4Front.Background = new SolidColorBrush(CoilsRes[Convert.ToUInt16(22)] ? Colors.Green : Colors.Red);
btn_ElectricMotor4Back.Background = new SolidColorBrush(CoilsRes[Convert.ToUInt16(23)] ? Colors.Green : Colors.Red);
}
else
{
btn_conn.Content = "连接";
}
}
else
{
ModbusHelper.master.Close();
if (ModbusHelper.master.IsOpen())
{
btn_conn.Content = "断开";
}
else
{
btn_conn.Content = "连接";
}
}
}
private void Button_Click(object sender, RoutedEventArgs e)
{
var btn = sender as Button;
//读取当前状态
DateTime dt = DateTime.Now;
var CoilsResBefor = ModbusHelper.ReadCoils(stationNo, Convert.ToUInt16(btn.Tag), 1);
Console.WriteLine("=================="+DateTime.Now.Subtract(dt).TotalMilliseconds);
Thread.Sleep(100);
//写入线圈
ModbusHelper.WriteSingleCoil(stationNo, Convert.ToUInt16(btn.Tag), !CoilsResBefor[0]);
Thread.Sleep(100);
//读取写入后状态
var CoilsRes = ModbusHelper.ReadCoils(stationNo, Convert.ToUInt16(btn.Tag), 1);
btn.Background = new SolidColorBrush(CoilsRes[0] ? Colors.Green : Colors.Red);
}
/// <summary>
/// 电机1正传
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Button_Click_1(object sender, RoutedEventArgs e)
{
ModbusHelper.WriteSingleCoil(stationNo, 17, false);
Thread.Sleep(100);
//读取当前状态
var CoilsResBefor = ModbusHelper.ReadCoils(stationNo, 16, 1);
Thread.Sleep(100);
//写入线圈
ModbusHelper.WriteSingleCoil(stationNo, 16, !CoilsResBefor[0]);
Thread.Sleep(100);
//读取写入后状态
var CoilsRes = ModbusHelper.ReadCoils(stationNo, 16, 1);
btn_ElectricMotor1Front.Background = new SolidColorBrush(CoilsRes[0] ? Colors.Green : Colors.Red);
}
/// <summary>
/// 电机1反传
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Button_Click_2(object sender, RoutedEventArgs e)
{
ModbusHelper.WriteSingleCoil(stationNo, 16, false);
Thread.Sleep(100);
//读取当前状态
var CoilsResBefor = ModbusHelper.ReadCoils(stationNo, 17, 1);
Thread.Sleep(100);
//写入线圈
ModbusHelper.WriteSingleCoil(stationNo, 17, !CoilsResBefor[0]);
Thread.Sleep(100);
//读取写入后状态
var CoilsRes = ModbusHelper.ReadCoils(stationNo, 17, 1);
btn_ElectricMotor1Back.Background = new SolidColorBrush(CoilsRes[0] ? Colors.Green : Colors.Red);
}
/// <summary>
/// 电机2正传
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Button_Click_3(object sender, RoutedEventArgs e)
{
ModbusHelper.WriteSingleCoil(stationNo, 19, false);
Thread.Sleep(100);
//读取当前状态
var CoilsResBefor = ModbusHelper.ReadCoils(stationNo, 18, 1);
Thread.Sleep(100);
//写入线圈
ModbusHelper.WriteSingleCoil(stationNo, 18, !CoilsResBefor[0]);
Thread.Sleep(100);
//读取写入后状态
var CoilsRes = ModbusHelper.ReadCoils(stationNo, 18, 1);
btn_ElectricMotor2Front.Background = new SolidColorBrush(CoilsRes[0] ? Colors.Green : Colors.Red);
}
/// <summary>
/// 电机2反传
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Button_Click_4(object sender, RoutedEventArgs e)
{
ModbusHelper.WriteSingleCoil(stationNo, 18, false);
Thread.Sleep(100);
//读取当前状态
var CoilsResBefor = ModbusHelper.ReadCoils(stationNo, 19, 1);
Thread.Sleep(100);
//写入线圈
ModbusHelper.WriteSingleCoil(stationNo, 19, !CoilsResBefor[0]);
Thread.Sleep(100);
//读取写入后状态
var CoilsRes = ModbusHelper.ReadCoils(stationNo, 19, 1);
btn_ElectricMotor2Back.Background = new SolidColorBrush(CoilsRes[0] ? Colors.Green : Colors.Red);
}
/// <summary>
/// 电机3正传
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Button_Click_5(object sender, RoutedEventArgs e)
{
ModbusHelper.WriteSingleCoil(stationNo, 21, false);
Thread.Sleep(100);
//读取当前状态
var CoilsResBefor = ModbusHelper.ReadCoils(stationNo, 20, 1);
Thread.Sleep(100);
//写入线圈
ModbusHelper.WriteSingleCoil(stationNo, 20, !CoilsResBefor[0]);
Thread.Sleep(100);
//读取写入后状态
var CoilsRes = ModbusHelper.ReadCoils(stationNo, 20, 1);
btn_ElectricMotor3Front.Background = new SolidColorBrush(CoilsRes[0] ? Colors.Green : Colors.Red);
}
/// <summary>
/// 电机3反传
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Button_Click_6(object sender, RoutedEventArgs e)
{
ModbusHelper.WriteSingleCoil(stationNo, 20, false);
Thread.Sleep(100);
//读取当前状态
var CoilsResBefor = ModbusHelper.ReadCoils(stationNo, 21, 1);
Thread.Sleep(100);
//写入线圈
ModbusHelper.WriteSingleCoil(stationNo, 21, !CoilsResBefor[0]);
Thread.Sleep(100);
//读取写入后状态
var CoilsRes = ModbusHelper.ReadCoils(stationNo, 21, 1);
btn_ElectricMotor3Back.Background = new SolidColorBrush(CoilsRes[0] ? Colors.Green : Colors.Red);
}
/// <summary>
/// 电机4正传
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Button_Click_7(object sender, RoutedEventArgs e)
{
ModbusHelper.WriteSingleCoil(stationNo, 23, false);
Thread.Sleep(100);
//读取当前状态
var CoilsResBefor = ModbusHelper.ReadCoils(stationNo, 22, 1);
Thread.Sleep(100);
//写入线圈
ModbusHelper.WriteSingleCoil(stationNo, 22, !CoilsResBefor[0]);
Thread.Sleep(100);
//读取写入后状态
var CoilsRes = ModbusHelper.ReadCoils(stationNo, 22, 1);
btn_ElectricMotor4Front.Background = new SolidColorBrush(CoilsRes[0] ? Colors.Green : Colors.Red);
}
/// <summary>
/// 电机4反传
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Button_Click_8(object sender, RoutedEventArgs e)
{
ModbusHelper.WriteSingleCoil(stationNo, 22, false);
Thread.Sleep(100);
//读取当前状态
var CoilsResBefor = ModbusHelper.ReadCoils(stationNo, 23, 1);
Thread.Sleep(100);
//写入线圈
ModbusHelper.WriteSingleCoil(stationNo, 23, !CoilsResBefor[0]);
Thread.Sleep(100);
//读取写入后状态
var CoilsRes = ModbusHelper.ReadCoils(stationNo, 23, 1);
btn_ElectricMotor4Back.Background = new SolidColorBrush(CoilsRes[0] ? Colors.Green : Colors.Red);
}
/// <summary>
/// 通道1速度
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Button_Click_9(object sender, RoutedEventArgs e)
{
ModbusHelper.WriteSingleRegister(stationNo, 23, Convert.ToUInt16(txt_channel1Speed.Text));
Thread.Sleep(100);
var res = ModbusHelper.ReadHoldingRegisters(stationNo, 23, 1);
txt_channel1Speed.Text = res[0].ToString();
}
/// <summary>
/// 通道2速度
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Button_Click_10(object sender, RoutedEventArgs e)
{
ModbusHelper.WriteSingleRegister(stationNo, 27, Convert.ToUInt16(txt_channel2Speed.Text));
Thread.Sleep(100);
var res = ModbusHelper.ReadHoldingRegisters(stationNo, 27, 1);
txt_channel2Speed.Text = res[0].ToString();
}
/// <summary>
/// 通道3速度
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Button_Click_11(object sender, RoutedEventArgs e)
{
ModbusHelper.WriteSingleRegister(stationNo, 31, Convert.ToUInt16(txt_channel3Speed.Text));
Thread.Sleep(100);
var res = ModbusHelper.ReadHoldingRegisters(stationNo, 31, 1);
txt_channel3Speed.Text = res[0].ToString();
}
/// <summary>
/// 通道4速度
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Button_Click_12(object sender, RoutedEventArgs e)
{
ModbusHelper.WriteSingleRegister(stationNo, 35, Convert.ToUInt16(txt_channel4Speed.Text));
Thread.Sleep(100);
var res = ModbusHelper.ReadHoldingRegisters(stationNo, 35, 1);
txt_channel4Speed.Text = res[0].ToString();
}
bool isStill = true;
Thread alwaysThread;
private void Button_Click_13(object sender, RoutedEventArgs e)
{
if (btn_always.Content.ToString() == "循环测试开始")
{
isStill = true;
btn_always.Content = "循环测试停止";
alwaysThread= new Thread(() =>
{
while (isStill)
{
for (int i = 0; i < 24; i++)
{
if (i == 17 || i == 19 || i == 21 || i == 23)
continue;
ModbusHelper.WriteSingleCoil(stationNo, (ushort)i, true);
Thread.Sleep(500);
}
Thread.Sleep(5000);
for (int i = 0; i < 24; i++)
{
ModbusHelper.WriteSingleCoil(stationNo, (ushort)i, false);
Thread.Sleep(500);
}
Thread.Sleep(5000);
}
});
alwaysThread.Start();
}
else
{
isStill = false;
btn_always.Content = "循环测试开始";
alwaysThread.Abort();
}
}
Thread FrontBackThread;
private void btn_FrontBack_Click(object sender, RoutedEventArgs e)
{
if (btn_FrontBack.Content.ToString() == "正反转测试开始")
{
isStill = true;
btn_FrontBack.Content = "正反转测试停止";
FrontBackThread= new Thread(() =>
{
while (isStill)
{
//启动通道
for (int i = 0; i < 16; i++)
{
ModbusHelper.WriteSingleCoil(stationNo, (ushort)i, true);
}
//正转测试
ModbusHelper.WriteSingleRegister(stationNo, 23, 30);
Thread.Sleep(1000);
ModbusHelper.WriteSingleCoil(stationNo, 16,true);
ModbusHelper.WriteSingleRegister(stationNo, 23, 100);
ModbusHelper.WriteSingleRegister(stationNo, 27, 30);
Thread.Sleep(1000);
ModbusHelper.WriteSingleCoil(stationNo, 18, true);
ModbusHelper.WriteSingleRegister(stationNo, 27, 100);
ModbusHelper.WriteSingleRegister(stationNo, 31, 30);
Thread.Sleep(1000);
ModbusHelper.WriteSingleCoil(stationNo, 20, true);
ModbusHelper.WriteSingleRegister(stationNo, 31, 100);
ModbusHelper.WriteSingleRegister(stationNo, 35, 30);
Thread.Sleep(1000);
ModbusHelper.WriteSingleCoil(stationNo, 22, true);
ModbusHelper.WriteSingleRegister(stationNo, 35, 100);
Thread.Sleep(2000);
//关闭正转
ModbusHelper.WriteSingleCoil(stationNo, 16, false);
ModbusHelper.WriteSingleCoil(stationNo, 18, false);
ModbusHelper.WriteSingleCoil(stationNo, 20, false);
ModbusHelper.WriteSingleCoil(stationNo, 22, false);
Thread.Sleep(1000);
//反转测试
ModbusHelper.WriteSingleRegister(stationNo, 23, 30);
Thread.Sleep(1000);
ModbusHelper.WriteSingleCoil(stationNo, 17, true);
ModbusHelper.WriteSingleRegister(stationNo, 23, 100);
ModbusHelper.WriteSingleRegister(stationNo, 27, 30);
Thread.Sleep(1000);
ModbusHelper.WriteSingleCoil(stationNo, 19, true);
ModbusHelper.WriteSingleRegister(stationNo, 27, 100);
ModbusHelper.WriteSingleRegister(stationNo, 31, 30);
Thread.Sleep(1000);
ModbusHelper.WriteSingleCoil(stationNo, 21, true);
ModbusHelper.WriteSingleRegister(stationNo, 31, 100);
ModbusHelper.WriteSingleRegister(stationNo, 35, 30);
Thread.Sleep(1000);
ModbusHelper.WriteSingleCoil(stationNo, 23, true);
ModbusHelper.WriteSingleRegister(stationNo, 35, 100);
Thread.Sleep(2000);
//关闭通道
for (int i = 0; i < 16; i++)
{
ModbusHelper.WriteSingleCoil(stationNo, (ushort)i, false);
}
//关闭反转
Thread.Sleep(2000);
ModbusHelper.WriteSingleCoil(stationNo, 17, false);
ModbusHelper.WriteSingleCoil(stationNo, 19, false);
ModbusHelper.WriteSingleCoil(stationNo, 21, false);
ModbusHelper.WriteSingleCoil(stationNo, 23, false);
Thread.Sleep(1000);
}
});
FrontBackThread.Start();
}
else
{
isStill = false;
btn_FrontBack.Content = "正反转测试开始";
FrontBackThread.Abort();
//停止通道
for (int i = 0; i < 24; i++)
{
ModbusHelper.WriteSingleCoil(stationNo, (ushort)i, false);
}
ModbusHelper.WriteSingleCoil(stationNo, 16, false);
ModbusHelper.WriteSingleCoil(stationNo, 18, false);
ModbusHelper.WriteSingleCoil(stationNo, 20, false);
ModbusHelper.WriteSingleCoil(stationNo, 22, false);
ModbusHelper.WriteSingleCoil(stationNo, 17, false);
ModbusHelper.WriteSingleCoil(stationNo, 19, false);
ModbusHelper.WriteSingleCoil(stationNo, 21, false);
ModbusHelper.WriteSingleCoil(stationNo, 23, false);
}
}
}
}

View File

@ -0,0 +1,84 @@

using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO.Ports;
using Modbus.Device;
using HslCommunication.ModBus; // 引入 NModbus 库
namespace ControlcBoardsTest
{
internal class ModbusHelper
{
/// <summary>
/// 私有ModbusRTU主站字段
/// </summary>
public static ModbusRtu master=new ModbusRtu(2);
/// <summary>
/// 写入单个线圈
/// </summary>
public static void WriteSingleCoil(byte stationNo, ushort Adr, bool Value)
{
master.Write(Adr.ToString(), Value);
}
public static StopBits GetSelectedStopBits(double stopBits)
{
switch (stopBits)
{
case 1:
return StopBits.One;
case 1.5:
return StopBits.OnePointFive;
case 2:
return StopBits.Two;
default:
return StopBits.One;
}
}
/// <summary>
/// 写入单个寄存器
/// </summary>
public static void WriteSingleRegister(byte stationNo, ushort Value, ushort result)
{
master.Write(Value.ToString(), result);
}
/// <summary>
/// 读取输出线圈
/// </summary>
/// <returns></returns>
public static bool[] ReadCoils(byte stationNo, ushort Value, ushort result)
{
var data = master.ReadCoil(Value.ToString(), result);
return master.ReadCoil(Value.ToString(), result).Content;
}
/// <summary>
/// 读取保持型寄存器
/// </summary>
/// <returns></returns>
public static ushort[] ReadHoldingRegisters(byte stationNo, ushort Value, ushort result)
{
return master.ReadUInt16(Value.ToString(), result).Content;
}
}
}

View File

@ -0,0 +1,52 @@
using System.Reflection;
using System.Resources;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Windows;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("ControlcBoardsTest")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ControlcBoardsTest")]
[assembly: AssemblyCopyright("Copyright © 2025")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 会使此程序集中的类型
//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
//若要开始生成可本地化的应用程序,请设置
//.csproj 文件中的 <UICulture>CultureYouAreCodingWith</UICulture>
//在 <PropertyGroup> 中。例如,如果你使用的是美国英语。
//使用的是美国英语,请将 <UICulture> 设置为 en-US。 然后取消
//对以下 NeutralResourceLanguage 特性的注释。 更新
//以下行中的“en-US”以匹配项目文件中的 UICulture 设置。
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //主题特定资源词典所处位置
//(未在页面中找到资源时使用,
//或应用程序资源字典中找到时使用)
ResourceDictionaryLocation.SourceAssembly //常规资源词典所处位置
//(未在页面中找到资源时使用,
//、应用程序或任何主题专用资源字典中找到时使用)
)]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@ -0,0 +1,63 @@
//------------------------------------------------------------------------------
// <auto-generated>
// 此代码由工具生成。
// 运行时版本:4.0.30319.42000
//
// 对此文件的更改可能会导致不正确的行为,并且如果
// 重新生成代码,这些更改将会丢失。
// </auto-generated>
//------------------------------------------------------------------------------
namespace ControlcBoardsTest.Properties {
using System;
/// <summary>
/// 一个强类型的资源类,用于查找本地化的字符串等。
/// </summary>
// 此类是由 StronglyTypedResourceBuilder
// 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。
// 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen
// (以 /str 作为命令选项),或重新生成 VS 项目。
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// 返回此类使用的缓存的 ResourceManager 实例。
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ControlcBoardsTest.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// 重写当前线程的 CurrentUICulture 属性,对
/// 使用此强类型资源类的所有资源查找执行重写。
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
}
}

View File

@ -0,0 +1,117 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>

View File

@ -0,0 +1,26 @@
//------------------------------------------------------------------------------
// <auto-generated>
// 此代码由工具生成。
// 运行时版本:4.0.30319.42000
//
// 对此文件的更改可能会导致不正确的行为,并且如果
// 重新生成代码,这些更改将会丢失。
// </auto-generated>
//------------------------------------------------------------------------------
namespace ControlcBoardsTest.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "17.11.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
}
}

View File

@ -0,0 +1,7 @@
<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="uri:settings" CurrentProfile="(Default)">
<Profiles>
<Profile Name="(Default)" />
</Profiles>
<Settings />
</SettingsFile>

View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="HslCommunication" version="12.2.0" targetFramework="net45" />
<package id="Newtonsoft.Json" version="13.0.1" targetFramework="net45" />
<package id="NModbus4" version="2.1.0" targetFramework="net45" />
</packages>