Animatroller.Simulator.Control.Motor.timer_Tick C# (CSharp) Method

timer_Tick() private method

private timer_Tick ( object state ) : void
state object
return void
        private void timer_Tick(object state)
        {
            if (Monitor.TryEnter(timer))
            {
                try
                {
                    if (Speed != 0 && !motorFailed)
                    {
                        if ((DateTime.Now - this.startTime) > Timeout)
                        {
                            motorFailed = true;
                            Speed = 0;
                            Trigger((int)CurrentPosition, motorFailed);
                            timer.Change(System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite);
                            return;
                        }

                        double distance = Math.Abs(Target - CurrentPosition);
                        if (distance <= 2)
                        {
                            // Stop
                            Speed = 0;
                            Trigger((int)CurrentPosition, motorFailed);
                            timer.Change(System.Threading.Timeout.Infinite, System.Threading.Timeout.Infinite);
                        }
                        else
                        {
                            // Ramp up/down
                            if (distance < 10)
                            {
                                // Slow down
                                if (currentSpeed > 0.1)
                                {
                                    currentSpeed -= 0.1;
                                    UpdateTrackbar();
                                }
                            }
                            else
                            {
                                // Speed up
                                if (currentSpeed < Speed)
                                {
                                    currentSpeed += 0.1;
                                    UpdateTrackbar();
                                }
                            }

                            if (Target < CurrentPosition)
                                CurrentPosition -= currentSpeed * 5;
                            else if (Target > CurrentPosition)
                                CurrentPosition += currentSpeed * 5;
                        }

                    }
                }
                finally
                {
                    Monitor.Exit(timer);
                }
            }
        }