【愚公系列】2023年08月 WPF运动控制平台-005.运动平台之功能实现(完结)

举报
愚公搬代码 发表于 2023/08/18 22:57:08 2023/08/18
【摘要】 一、运动平台之功能实现 1.位置计算物理可用距离 (40000), 取料位:19945P, 打包位:-19360P像素位置:取料位:20px 打包位:1020px把脉冲转换位距离步进驱动器设置细分 8步进电机步进角 1.8°导程:8mm计算步进电机走1cm需要的脉冲数360 / 1.8 = 200个脉冲转一圈200 * 8 = 1600个脉冲转一圈(细分情况)1600 / 8 = 2...

一、运动平台之功能实现

1.位置计算

  1. 物理可用距离 (40000), 取料位:19945P, 打包位:-19360P

  2. 像素位置:取料位:20px 打包位:1020px

  3. 把脉冲转换位距离

    1. 步进驱动器设置细分 8

    2. 步进电机步进角 1.8°

    3. 导程:8mm

      计算步进电机走1cm需要的脉冲数

      360 / 1.8 = 200个脉冲转一圈

      200 * 8 = 1600个脉冲转一圈(细分情况)

      1600 / 8 = 200 (步进电机走1mm需要)

      故:走1cm需要脉冲数 200 * 10 = 2000个脉冲

      取料位实际距离:19945 / 2000 = 9.9725cm

      打包位实际距离:19360 / 2000 = 9.68cm

  4. 计算物理小车移动距离与图像小车移动距离

    y = kx + b

    y 小车在软件中位置,x在物理的实际位置

    像素可用距离:1000px

    物理可用距离:9.9725+9.68 = 19.6525

    k = 1000/ 19.6525 = 50.88411143620405

    B = 1020 - 50.88411143620405 * 9.68 = 527.4418012975448

二、代码

具体封装代码上篇文章有,实际功能完整代码如下:

<Window x:Class="Zhaoxi.Motion.CorePlat.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:Zhaoxi.Motion.CorePlat"
        mc:Ignorable="d"
        Title="MainWindow" WindowStyle="None" ResizeMode="CanResizeWithGrip" AllowsTransparency="True"
        WindowStartupLocation="CenterScreen"
        Height="650" Width="1200" Loaded="Window_Loaded" MouseLeftButtonDown="Window_MouseLeftButtonDown">
    <Window.Resources>
        <Style x:Key="FontStyle" TargetType="Label">
            <Setter Property="FontFamily" Value="Microsoft YA Hei" />
            <Setter Property="FontSize" Value="20" />
            <Setter Property ="Foreground"  Value ="#E2E6E9" />
        </Style>
        <Style TargetType ="Hyperlink">
            <!-- 清除文字修饰(去掉下划线) -->
            <Setter Property ="TextBlock.TextDecorations" Value ="{x:Null}" />
            <Style.Triggers>
                <Trigger Property ="IsMouseOver" Value ="True">
                    <!-- 在鼠标悬停时显示下划线 -->
                    <Setter Property ="TextBlock.TextDecorations">
                        <Setter.Value >
                            <TextDecorationCollection>
                                <TextDecoration Location ="Underline" />
                            </TextDecorationCollection>
                        </Setter.Value>
                    </Setter>
                </Trigger>
            </Style.Triggers>
        </Style>
        <Style TargetType="DataGrid">
            <Setter Property="RowHeaderWidth" Value="0"></Setter>
            <Setter Property="AutoGenerateColumns" Value="False"></Setter>
            <Setter Property="CanUserAddRows" Value="False"></Setter>
            <Setter Property="CanUserResizeColumns" Value="False"></Setter>
            <Setter Property="CanUserResizeRows" Value="False"></Setter>
            <Setter Property="HorizontalGridLinesBrush" Value="#496D87"></Setter>
            <Setter Property="VerticalGridLinesBrush" Value="#496D87"></Setter>
            <Setter Property="IsReadOnly" Value="True"></Setter>
            <Setter Property="BorderThickness" Value="0"></Setter>
            <Setter Property="BorderBrush" Value="#496D87"></Setter>
            <Setter Property="RowHeight" Value="30"></Setter>
            <Setter Property="VerticalScrollBarVisibility" Value="Auto"></Setter>
            <Setter Property="Background" Value="Transparent"></Setter>
            <Setter Property="GridLinesVisibility" Value="None" />
        </Style>

        <!--DataGrid表头样式-->
        <Style TargetType="DataGridColumnHeader">
            <Setter Property="Foreground" Value="#6F899D" />
            <Setter Property="FontSize" Value="14"></Setter>
            <Setter Property="Background" Value="Transparent"></Setter>
            <Setter Property="BorderThickness" Value="0 0 0 1"></Setter>
            <Setter Property="BorderBrush" Value="#496D87"></Setter>
            <Setter Property="HorizontalContentAlignment" Value="Center"></Setter>
            <Setter Property="Height" Value="30" />
        </Style>
        <Style x:Key="DataRowStyle" TargetType="{x:Type DataGridRow}">
            <Setter Property="Background" Value="Transparent"/>
            <Setter Property="Foreground" Value="White"/>
            <Setter Property="BorderThickness" Value="0" />
        </Style>
        <Style x:Key="DataCellStyle" TargetType="{x:Type DataGridCell}">
            <Setter Property="HorizontalAlignment" Value="Center"/>
            <Setter Property="VerticalAlignment" Value="Center"/>
            <Setter Property="BorderThickness" Value="0"></Setter>
        </Style>
        <Style TargetType="Button">
            <Setter Property="Width" Value="80" />
            <Setter Property="Height" Value="32" />
            <Setter Property="Background" Value="#AAAAAA" />
            <Setter Property="Foreground" Value="#DADADA" />
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type Button}">
                        <Border x:Name="Border" CornerRadius="5" Background="{TemplateBinding Background}" TextBlock.Foreground="{TemplateBinding Foreground}">
                            <!--设置控件的边框,圆角,背景色,字体颜色-->
                            <ContentPresenter Margin="{TemplateBinding Padding}" HorizontalAlignment="Center" VerticalAlignment="Center">
                                <!--显示控件的内容-->
                            </ContentPresenter>
                        </Border>
                        <ControlTemplate.Triggers>
                            <Trigger Property="IsMouseOver" Value="True">
                                <Setter Property="Background" Value="#faa755"/>
                                <Setter Property="Foreground" Value="#FADCB2"/>
                            </Trigger>
                            <Trigger Property="IsPressed" Value="True">
                                <Setter Property="Background" Value="#F29701"/>
                                <Setter Property="Foreground" Value="#FADCB2"/>
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Window.Resources>
    <Grid>
        <Grid.Background>
            <LinearGradientBrush StartPoint="1, 0" EndPoint="0 , 1">
                <GradientStop Color="#365B74" Offset="0.2" />
                <GradientStop Color="#4A6E87" Offset="1"/>
            </LinearGradientBrush>
        </Grid.Background>
        <Grid.RowDefinitions>
            <RowDefinition Height="0.5*" />
            <RowDefinition Height="2.5*" />
            <RowDefinition Height="0.4*"/>
            <RowDefinition Height="2*"/>
            <RowDefinition Height="0.3*"/>
        </Grid.RowDefinitions>
        <Grid Grid.Row="0">
            <Border BorderBrush="#74848F" BorderThickness="0 0 0 2" Margin="30 0 30 0" />
            <Image Width="60" Height="45" Margin="30 0 20 0" HorizontalAlignment="Left" Source="pack://application:,,,/Zhaoxi.Motion.CorePlat;component/Assets/Images/logo.png" />
            <Label Margin="100 0 0 0" HorizontalAlignment="Left" Style="{StaticResource FontStyle}" Content="朝夕运动控制平台" Foreground="#E2E6E9" VerticalAlignment="Center" />
            <TextBlock HorizontalAlignment="Right" FontSize="16" Margin="0 0 30 0" VerticalAlignment="Center">
                <Hyperlink Foreground="#FFEAE5E3" Click="Hyperlink_Click">[退出]</Hyperlink>
            </TextBlock>
        </Grid>
        <Grid Grid.Row="1" Margin="50 10 50 10">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="1*" />
                <ColumnDefinition Width="2*"/>
                <ColumnDefinition Width="1*" />
            </Grid.ColumnDefinitions>
            <Border Margin="5" BorderBrush="#569BAC" CornerRadius="5" BorderThickness="1" Grid.Column="0">
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="40" />
                        <RowDefinition />
                        <RowDefinition />
                        <RowDefinition />
                    </Grid.RowDefinitions>
                    <StackPanel Grid.Row="0" Orientation="Horizontal">
                        <Line X1="8" Y1="8" X2="8" Y2="30" Stroke="#00F6FB" StrokeThickness="4"  />
                        <TextBlock Margin="20 0 0 0" Text="实时状态" FontSize="20" Foreground="#9FB1BF" HorizontalAlignment="Center" VerticalAlignment="Center" />
                    </StackPanel>
                    <StackPanel  Grid.Row="1">
                        <TextBlock Text="当前位置" Margin="30 0" FontSize="14" Foreground="#718A9F" />
                        <WrapPanel Margin="90 0 0 0">
                            <TextBlock Text="{Binding RealLocation}" FontSize="30" Foreground="#C1CCD5"  />
                            <TextBlock Margin="20 5 0 0" Text="cm" VerticalAlignment="Center" FontSize="18" Foreground="#9DAFBC" />
                        </WrapPanel>
                    </StackPanel>
                    <StackPanel  Grid.Row="2">
                        <TextBlock Text="当前速度" Margin="30 0" FontSize="14" Foreground="#718A9F" />
                        <WrapPanel Margin="90 0 0 0">
                            <TextBlock Text="{Binding RealSpeed}" FontSize="30" Foreground="#C1CCD5"  />
                            <TextBlock Margin="20 5 0 0" Text="cm/s" VerticalAlignment="Center" FontSize="18" Foreground="#9DAFBC" />
                        </WrapPanel>
                    </StackPanel>
                    <StackPanel  Grid.Row="3">
                        <TextBlock Text="运动状态" Margin="30 0" FontFamily="Microsoft Ya Hei" FontSize="14" Foreground="#718A9F" />
                        <WrapPanel Margin="90 0 0 0">
                            <TextBlock Text="{Binding RunState}"  FontSize="30" Foreground="#4DCBA8"  />
                        </WrapPanel>
                    </StackPanel>
                </Grid>
            </Border>
            <Border Margin="5" BorderBrush="#569BAC" CornerRadius="5" BorderThickness="1" Grid.Column="1">
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="40" />
                        <RowDefinition />
                    </Grid.RowDefinitions>
                    <StackPanel Grid.Row="0" Orientation="Horizontal">
                        <Line X1="8" Y1="8" X2="8" Y2="30" Stroke="#00F6FB" StrokeThickness="4"  />
                        <TextBlock Margin="20 0 0 0" Text="实时信息提示" FontSize="20" Foreground="#9FB1BF" HorizontalAlignment="Center" VerticalAlignment="Center" />
                    </StackPanel>
                    <DataGrid Margin="1" ItemsSource="{Binding Loggers}" Grid.Row="1" CellStyle="{StaticResource DataCellStyle}" RowStyle="{StaticResource DataRowStyle}">
                        <DataGrid.Columns>
                            <DataGridTextColumn Width="2.5*" Binding="{Binding LogTime}" Header="时间"/>
                            <DataGridTextColumn Width="5*" Binding="{Binding LogMessage}" Header="消息"/>
                            <DataGridTextColumn Width="*" Binding="{Binding LogType}" Header="类型"/>
                            <DataGridTextColumn Width="*" Binding="{Binding LogLevel}" Header="等级"/>
                        </DataGrid.Columns>
                    </DataGrid>
                </Grid>
            </Border>
            <Border Margin="5" BorderBrush="#569BAC" CornerRadius="5" BorderThickness="1" Grid.Column="2">
                <Grid>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="40" />
                        <RowDefinition />
                        <RowDefinition />
                        <RowDefinition />
                    </Grid.RowDefinitions>
                    <StackPanel Grid.Row="0" Orientation="Horizontal">
                        <Line X1="8" Y1="8" X2="8" Y2="30" Stroke="#00F6FB" StrokeThickness="4"  />
                        <TextBlock Margin="20 0 0 0" Text="参数配置" FontSize="20" Foreground="#9FB1BF" HorizontalAlignment="Center" VerticalAlignment="Center" />
                    </StackPanel>
                    <StackPanel  Grid.Row="1">
                        <TextBlock Text="取料速度" Margin="30 0 0 8" FontSize="14" Foreground="#718A9F" />
                        <WrapPanel>
                            <TextBox Text="{Binding RecpSpeed}" VerticalContentAlignment="Center" HorizontalContentAlignment="Left" Margin="30 0 0 0" Background="#CFD7DD" Width="150">
                                <TextBox.Resources>
                                    <Style TargetType="{x:Type Border}">
                                        <Setter Property="CornerRadius" Value="5"/>
                                    </Style>
                                </TextBox.Resources>
                            </TextBox>
                            <TextBlock Margin="20 5 0 0" Text="cm/s" VerticalAlignment="Center" FontSize="18" Foreground="#9DAFBC" />
                        </WrapPanel>
                    </StackPanel>
                    <StackPanel  Grid.Row="2">
                        <TextBlock Text="加工速度" Margin="30 0 0 8" FontSize="14" Foreground="#718A9F" />
                        <WrapPanel>
                            <TextBox Text="{Binding ProcessSpeed}" VerticalContentAlignment="Center" HorizontalContentAlignment="Left" Margin="30 0 0 0" Background="#CFD7DD" Width="150">
                                <TextBox.Resources>
                                    <Style TargetType="{x:Type Border}">
                                        <Setter Property="CornerRadius" Value="5"/>
                                    </Style>
                                </TextBox.Resources>
                            </TextBox>
                            <TextBlock Margin="20 5 0 0" Text="cm/s" VerticalAlignment="Center" FontSize="18" Foreground="#9DAFBC" />
                        </WrapPanel>
                    </StackPanel>
                    <StackPanel  Grid.Row="3">
                        <TextBlock Text="加工位置" Margin="30 0 0 8" FontSize="14" Foreground="#718A9F" />
                        <WrapPanel>
                            <TextBox Text="{Binding ProcessLocation}" VerticalContentAlignment="Center" HorizontalContentAlignment="Left" Margin="30 0 0 0" Background="#CFD7DD" Width="150">
                                <TextBox.Resources>
                                    <Style TargetType="{x:Type Border}">
                                        <Setter Property="CornerRadius" Value="5"/>
                                    </Style>
                                </TextBox.Resources>
                            </TextBox>
                            <TextBlock Margin="20 5 0 0" Text="cm" VerticalAlignment="Center" FontSize="18" Foreground="#9DAFBC" />
                        </WrapPanel>
                    </StackPanel>
                </Grid>
            </Border>
        </Grid>
        <Grid Grid.Row="2" Margin="50 0 50 0" VerticalAlignment="Center">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="1*" />
                <ColumnDefinition Width="0.6*"/>
                <ColumnDefinition Width="0.6*"/>
                <ColumnDefinition Width="0.6*"/>
                <ColumnDefinition Width="2*"/>
                <ColumnDefinition />
                <ColumnDefinition />
                <ColumnDefinition />
            </Grid.ColumnDefinitions>
            <Button Name="Btn_Start" Width="130" Content="启动系统" Grid.Column="0" Height="NaN" Margin="6,2,5,1" Click="Btn_Start_Click" />
            <Button Name="Btn_Recp" Content="去取料" Grid.Column="1" Click="Btn_Recp_Click" />
            <Button Name="Btn_Pack" Content="去打包" Grid.Column="2" Click="Btn_Pack_Click" />
            <Button Name="Btn_Tag" Content="贴标签" Grid.Column="3" Click="Btn_Tag_Click"/>
            <WrapPanel Grid.Column="5" VerticalAlignment="Center" HorizontalAlignment="Center">
                <TextBlock Text="去取料" VerticalAlignment="Center" Foreground="#BBC2C8" />
                <Rectangle Name="RecpLight" Margin="10 0 0 0" Width="80" Height="35" Fill="#BBC2C8" RadiusX="5" RadiusY="5" />
            </WrapPanel>
            <WrapPanel Grid.Column="6" VerticalAlignment="Center" HorizontalAlignment="Center">
                <TextBlock Text="去打包" VerticalAlignment="Center" Foreground="#BBC2C8" />
                <Rectangle  Name="PackLight" Margin="10 0 0 0" Width="80" Height="35" Fill="#BBC2C8" RadiusX="5" RadiusY="5" />
            </WrapPanel>
            <WrapPanel Grid.Column="7" VerticalAlignment="Center" HorizontalAlignment="Center">
                <TextBlock Text="贴标签" VerticalAlignment="Center" Foreground="#BBC2C8" />
                <Rectangle Name="MarkTagLight" Margin="10 0 0 0" Width="80" Height="35" Fill="#BBC2C8" RadiusX="5" RadiusY="5" />
            </WrapPanel>
        </Grid>
        <Grid Grid.Row="3">
            <Border BorderBrush="#1A305F" BorderThickness="0 0 0 10" />
            <Canvas>
                <Viewbox Name="MoveRegion" Width="150" Height="150" Canvas.Left="{Binding CarLocation}" Canvas.Top="77">
                    <Grid RenderTransformOrigin="0.5,0.5">
                        <Grid.RenderTransform>
                            <ScaleTransform ScaleX="{Binding CarDirection}" />
                        </Grid.RenderTransform>
                        <Path Data="M254.464 668.672c-60.928 0-110.592 49.664-110.592 110.592 0 60.928 49.664 110.592 110.592 110.592 60.928 0 110.592-49.664 110.592-110.592-0.512-61.44-49.664-110.592-110.592-110.592z" Fill="#135173" />
                        <Path Data="M850.944 487.936h-20.992l-194.56-206.336-0.512-0.512c-24.064-24.576-57.344-38.4-91.648-37.888h-245.76c-43.008 0-82.944 22.016-105.984 58.368l-1.024 1.536-84.48 184.832h-50.176c-28.16 0-50.688 22.528-50.688 50.688v135.168c0 60.416 48.128 110.08 108.032 112.64v-7.168c0-77.824 62.976-141.312 141.312-141.312s141.312 62.976 141.312 141.312v7.168h262.144v-7.168c1.536-77.824 66.048-139.776 144.384-138.24 75.776 1.536 136.704 62.464 138.24 138.24v7.168h34.304c23.552 0 43.008-19.456 43.008-43.008v-90.112c-0.512-91.648-75.264-165.376-166.912-165.376z m-677.376 0L244.736 332.8c11.776-17.408 31.744-28.16 52.736-28.16H404.48v183.296H173.568z m292.352 0V304.64h76.8c17.92 0 35.328 7.168 48.128 19.968l154.624 163.328H465.92z" Fill="#135173" />
                        <Path Data="M798.72 668.672c-60.928 0-110.592 49.664-110.592 110.592 0 60.928 49.664 110.592 110.592 110.592 60.928 0 110.592-49.664 110.592-110.592 0-61.44-49.664-110.592-110.592-110.592z" Fill="#135173" />
                    </Grid>
                </Viewbox>
                <StackPanel Canvas.Left="85" Canvas.Top="40">
                    <Ellipse Name="RecpPoint" Fill="#A0A0A0" Width="20" Height="20" />
                    <Line X1="10" Y1="3" X2="10" Y2="150" Stroke="#A5AEB4" StrokeThickness="2" StrokeDashArray="7" />
                </StackPanel>
                <StackPanel Canvas.Left="585" Canvas.Top="40">
                    <Ellipse Name="HomePoint" Fill="#A0A0A0" Width="20" Height="20" />
                    <Line X1="10" Y1="3" X2="10" Y2="150" Stroke="#A5AEB4" StrokeThickness="2" StrokeDashArray="7" />
                </StackPanel>
                <StackPanel Canvas.Left="790" Canvas.Top="40">
                    <Ellipse Name="TagPoint" Fill="#A0A0A0" Width="20" Height="20" />
                    <Line X1="10" Y1="3" X2="10" Y2="150" Stroke="#A5AEB4" StrokeThickness="2" StrokeDashArray="7" />
                </StackPanel>
                <StackPanel Canvas.Left="1085" Canvas.Top="40">
                    <Ellipse Name="PackPoint" Fill="#A0A0A0" Width="20" Height="20" />
                    <Line X1="10" Y1="3" X2="10" Y2="150" Stroke="#A5AEB4" StrokeThickness="2" StrokeDashArray="7" />
                </StackPanel>
            </Canvas>
        </Grid>
        <Canvas Grid.Row="4" Background="#91A6B4" Margin="0 2 0 0">
            <TextBlock Canvas.Left="80" Canvas.Top="6" Text="取料" FontSize="16" Foreground="#DEE4E8" />
            <TextBlock Canvas.Left="580" Canvas.Top="6" Text="原点" FontSize="16" Foreground="#DEE4E8" />
            <TextBlock Canvas.Left="780" Canvas.Top="6" Text="贴标签" FontSize="16" Foreground="#DEE4E8" />
            <TextBlock Canvas.Left="1080" Canvas.Top="6" Text="打包" FontSize="16" Foreground="#DEE4E8" />
        </Canvas>
    </Grid>
</Window>


using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
using Zhaoxi.Motion.ControlLib;
using static gts.mc;

namespace Zhaoxi.Motion.CorePlat
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window, INotifyPropertyChanged
    {
        public ObservableCollection<MotionLogger> Loggers { get; set; } = new ObservableCollection<MotionLogger>();
        /// <summary>
        /// 定义点位目标的常量
        /// </summary>
        const int RECP_POS = 19360;
        const int PACK_POS = -19360;
        const int MTAG_POS = -8000;

        // 创建定时器对象
        private DispatcherTimer timer = new DispatcherTimer();
        private IAxisTool axisTool;
        private WorkState workState = WorkState.None;
        private double encPos;

        private double _realLocation = 0;
        private double _realSpeed = 0;
        private string _runState = "停止";
        // 系统默认的速度
        private double defaulVel = 8;
        // 系统默认颜色
        private Brush pointLightNewBrush;
        private Brush pointLightOldBrush;
        private Brush processLightBrush;
        // 记录小车的开始位置
        private double _carLocation;
        private int _carDirection = 1;

        /// <summary>
        /// 参数设置相关的字段
        /// </summary>
        private double _recpSpeed;
        private double _processSpeed;
        private double _processLocation;

        public event PropertyChangedEventHandler PropertyChanged;

        public void RiseProperty(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        public double RealLocation
        {
            get { return _realLocation; }
            set { _realLocation = value; RiseProperty(nameof(RealLocation)); }
        }

        public double RealSpeed
        {
            get { return _realSpeed; }
            set { _realSpeed = value; RiseProperty(nameof(RealSpeed)); }
        }
        public string RunState
        {
            get { return _runState; }
            set { _runState = value; RiseProperty(nameof(RunState)); }
        }

        public double RecpSpeed
        {
            get { return _recpSpeed; }
            set { _recpSpeed = value; RiseProperty(nameof(RecpSpeed)); }
        }

        public double ProcessSpeed
        {
            get { return _processSpeed; }
            set { _processSpeed = value; RiseProperty(nameof(ProcessSpeed)); }
        }

        public double ProcessLocation
        {
            get { return _processLocation; }
            set { _processLocation = value; RiseProperty(nameof(ProcessLocation)); }
        }

        public double CarLocation
        {
            get { return _carLocation; }
            set { _carLocation = value; RiseProperty(nameof(CarLocation)); }
        }

        public int CarDirection
        {
            get { return _carDirection; }
            set { _carDirection = value; RiseProperty(nameof(CarDirection)); }
        }


        public MainWindow()
        {
            InitializeComponent();
            // 设置DataContext
            DataContext = this;
            // 调用初始化方法
            InitData();
        }

        private void InitData()
        {
            // 定时器配置及启动
            timer.Interval = TimeSpan.FromMilliseconds(10);
            timer.Tick += Timer_Tick;
            timer.Start();

            // 创建对应轴卡的实例对象
            axisTool = AxisToolFactory.CreateInstance(AxisType.GTS800);
            // 初始化轴卡
            axisTool.AxisInit(1);

        }

        /// <summary>
        /// 刷新小车位置和监控轴状态
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <exception cref="NotImplementedException"></exception>
        private void Timer_Tick(object sender, EventArgs e)
        {
            // 获取小车物理实际移动位置
            axisTool.GetAxisEncPos(1, out encPos);
            // 8p/ms => 8000p/s =>  (8000 / 2000) = 4cm/s
            axisTool.GetAxisEncVel(1, out double encVel);
            // 计算速度
            var speed = encVel * 1000 / 2000;
            // 获取物理位置
            var location = encPos / 2000;
            // 给当前位置赋值
            RealLocation = Math.Round(location, 2);
            // 给当前速度属性赋值
            RealSpeed = Math.Abs(Math.Round(speed, 2));
            // 计算小车在软件的位置
            CarLocation = -50.88411143620405 * location + 527.4418012975448;
            CarDirectionLocation();
            // 根据速度设置运行状态
            if (speed != 0)
            {
                RunState = "运行";
            }
            else
            {
                RunState = "停止";
            }
            switch (workState)
            {
                case WorkState.Package:
                    if (encPos == PACK_POS)
                    {
                        PackPoint.Fill = pointLightNewBrush;
                        PackLight.Fill = processLightBrush;
                    }
                    else
                    {
                        PackLight.Fill = Brushes.Tomato;
                    }
                    break;
                case WorkState.MarkTag:
                    if (encPos == MTAG_POS)
                    {
                        TagPoint.Fill = pointLightNewBrush;
                        MarkTagLight.Fill = processLightBrush;
                    }
                    else
                    {
                        MarkTagLight.Fill = Brushes.Gold;
                    }
                    break;
                case WorkState.Recplier:
                    if (encPos == RECP_POS)
                    {
                        RecpPoint.Fill = pointLightNewBrush;
                        RecpLight.Fill = processLightBrush;
                    }
                    else
                    {
                        RecpLight.Fill = Brushes.DodgerBlue;
                    }
                    break;
                case WorkState.Home:
                    if (encPos == 0)
                    {
                        HomePoint.Fill = pointLightNewBrush;
                    }
                    break;
                default:
                    break;
            }



        }
        /// <summary>
        /// 重置到点指示灯的功能
        /// </summary>
        private void ResetPointLight()
        {
            HomePoint.Fill = pointLightOldBrush;
            RecpPoint.Fill = pointLightOldBrush;
            TagPoint.Fill = pointLightOldBrush;
            PackPoint.Fill = pointLightOldBrush;
        }

        /// <summary>
        /// 退出应用程序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Hyperlink_Click(object sender, RoutedEventArgs e)
        {
            // 停止轴
            axisTool.StopAxis(1);
            // 关闭轴卡
            axisTool.CloseAxis();
            // 关闭应用程序
            Application.Current.Shutdown();
        }

        private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            this.DragMove();
        }

        /// <summary>
        /// 系统启动
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_Start_Click(object sender, RoutedEventArgs e)
        {
            Loggers.Add(new MotionLogger
            {
                LogTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                LogMessage = "执行启动系统功能",
                LogLevel = 1,
                LogType = "INFO"
            });
            // 调用回原点方法
            // 创建运动参数对象
            var param = new AxisParameter
            {
                acc = 0.4,
                dec = 0.4,
                velStart = 0,
                smoothTime = 20
            };
            // 启动定时器
            timer.Start();
            // 执行回原操作
            axisTool.AxisGoHome(1, param, defaulVel, 3);
            // 切换位回原状态
            workState = WorkState.Home;
            // 调用重置到点指示灯的方法
            ResetPointLight();
        }

        /// <summary>
        /// 设置目标位置的点位运动
        /// </summary>
        /// <param name="pos"></param>
        private void SetPos(int pos)
        {
            double runVel = 0; // 运行速度
            // 重置到点指示灯颜色
            ResetPointLight();
            switch (workState)
            {
                case WorkState.None:
                    runVel = defaulVel;
                    break;
                case WorkState.Package:
                case WorkState.MarkTag:
                    runVel = ProcessSpeed;
                    break;
                case WorkState.Recplier:
                    runVel = RecpSpeed;
                    break;
            }
            // 创建运动参数对象
            var param = new AxisParameter
            {
                acc = 0.2,
                dec = 0.2,
                velStart = 0,
                smoothTime = 25
            };
            // 设置绝对运动目标位置
            // 8p / ms => 8000p / s =>  (8000 / 2000) = 4cm / s
            // 走4cm = > 8000p / s => 8 p / ms
            // runvel * 2000 / 1000
            var pVel = runVel * 2000 / 1000;
            axisTool.AxisAbsMove(1, param, pos, pVel);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_Pack_Click(object sender, RoutedEventArgs e)
        {
            if (RealSpeed == 0)
            {
                Loggers.Add(new MotionLogger
                {
                    LogTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                    LogMessage = "执行打包工序",
                    LogLevel = 0,
                    LogType = "INFO"
                });

                workState = WorkState.Package;
                SetPos(PACK_POS);
            }

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_Recp_Click(object sender, RoutedEventArgs e)
        {
            if (RealSpeed == 0)
            {
                Loggers.Add(new MotionLogger
                {
                    LogTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                    LogMessage = "执行取料工序",
                    LogLevel = 0,
                    LogType = "INFO"
                });
                workState = WorkState.Recplier;
                SetPos(RECP_POS);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Btn_Tag_Click(object sender, RoutedEventArgs e)
        {
            if (RealSpeed == 0)
            {
                Loggers.Add(new MotionLogger
                {
                    LogTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                    LogMessage = "执行贴标签工序",
                    LogLevel = 0,
                    LogType = "INFO"
                });
                workState = WorkState.MarkTag;
                SetPos(MTAG_POS);
            }
        }
        /// <summary>
        /// 做数据的初始化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            Loggers.Add(new MotionLogger
            {
                LogTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                LogMessage = "执行系统数据初始化",
                LogLevel = 0,
                LogType = "INFO"
            });

            // 初始化配置参数
            ProcessLocation = 4;
            ProcessSpeed = 4;
            RecpSpeed = 4;
            // 初始化到点指示灯的颜色
            pointLightOldBrush = new SolidColorBrush(Color.FromRgb(160, 160, 160));
            pointLightNewBrush = new SolidColorBrush(Color.FromRgb(77, 203, 168));
            processLightBrush = new SolidColorBrush(Color.FromRgb(187, 194, 200));
            // 获取小车物理实际移动位置
            axisTool.GetAxisEncPos(1, out encPos);
            // 在启动系统的时候初始化到点指示灯状态
            if (encPos == 0)
            {
                workState = WorkState.Home;
            }
            else if (encPos == MTAG_POS)
            {
                workState = WorkState.MarkTag;
            }
            else if (encPos == RECP_POS)
            {
                workState = WorkState.Recplier;
            }
            else if (encPos == PACK_POS)
            {
                workState = WorkState.Package;
            }
        }

        double oldValue = 0;
        /// <summary>
        /// 判断轴卡输出的是正脉冲还是负脉冲
        /// </summary>
        /// <param name="flag"></param>
        public void CarDirectionLocation()
        {
            Task.Run(() =>
            {
                while (RealSpeed != 0)
                {
                    double newValue = 0;
                    var result = GT_GetEncPos(1, out newValue, 1, out uint clk);
                    if (result != 0)
                    {
                        Console.WriteLine("Failed to get encoder position!");
                        break;
                    }

                    if (newValue > oldValue)
                    {

                        CarDirection = -1;
                    }
                    else if (newValue < oldValue)
                    {
                        CarDirection = 1;
                    }
                    oldValue = newValue;
                }
            });
        }
    }
}

在这里插入图片描述

【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。