Exemplo n.º 1
0
        /// <summary>
        /// Waits for a button to turn from false to true, then turns a lamp on, and after that turns the lamp on or off
        /// on every change of the button.
        /// </summary>
        /// <param name="button">The button to use.</param>
        /// <param name="lamp">The lamp to use.</param>
        public static void Run(IBooleanInput button, IBooleanOutput lamp)
        {
            // Check parameters:
            if (button == null)
            {
                throw new ArgumentNullException(nameof(button));
            }
            if (lamp == null)
            {
                throw new ArgumentNullException(nameof(lamp));
            }

            // Wait for the button to turn from false to true (test this holding the button when the program starts!):
            button.WaitFor(true, true);
            lamp.Value = true;

            // Wait for the button to change to any value and set the lamp accordingly.
            while (true)
            {
                lamp.Value = button.WaitForChange();
            }
        }
        /// <summary>
        /// Runs a "Turmbergbahn" train, that is, 2 trains hanging on a single steel wire driven by a motor, running on
        /// the same rails using a "Abt'sche Weiche".
        /// </summary>
        /// <param name="trainMotor">The motor driving both trains at once. +1.0 is output for the direction so that
        /// train 1 drives upwards and train 2 drives downwards, -1.0 vice versa.</param>
        /// <param name="train1ReachedBottomStation">Signals true when train 1 reached the bottom station (and thus
        /// train 2 reached the top station).</param>
        /// <param name="train2ReachedBottomStation">Signals true when train 2 reached the bottom station (and thus
        /// train 1 reached the top station).</param>
        /// <param name="doorMotor">The motor driving all doors on both trains at once. +1.0 is output for opening,
        /// -1.0 for closing.</param>
        /// <param name="redLight">True shall light up a red traffic light when people shall not enter or leave the
        /// train.</param>
        /// <param name="greenLight">True shall light up a green traffic light when people may enter or leave the
        /// train.</param>
        /// <param name="waitForDoorsToMoveInMs">The time, in milliseconds, to wait for the
        /// <paramref name="doorMotor"/> to have operated all doors reliably.</param>
        /// <param name="waitWithOpenDoorsInMs">The time, in milliseconds, that the doors shall remain open.</param>
        /// <param name="waitAroundDoorOperationsInMs">The time, in milliseconds, to wait after the train stopped and
        /// before opening the door, and after the doors were closed again before the train starts.</param>
        public static void Run(ISingleOutput trainMotor,
                               IBooleanInput trainReachedBottomStation,
                               ISingleOutput doorMotor,
                               int waitForDoorsToMoveInMs,
                               int waitWithOpenDoorsInMs,
                               int waitAroundDoorOperationsInMs)
        {
            // Check arguments:

            if (trainMotor == null)
            {
                throw new ArgumentNullException(nameof(trainMotor));
            }
            if (trainReachedBottomStation == null)
            {
                throw new ArgumentNullException(nameof(trainReachedBottomStation));
            }
            if (doorMotor == null)
            {
                throw new ArgumentNullException(nameof(doorMotor));
            }
            if (waitForDoorsToMoveInMs < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(waitForDoorsToMoveInMs));
            }
            if (waitWithOpenDoorsInMs < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(waitWithOpenDoorsInMs));
            }
            if (waitAroundDoorOperationsInMs < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(waitAroundDoorOperationsInMs));
            }

            // Run the train:

            float moveDirection = 1.0f;

            while (true)
            {
                // Move the train in the current direction until one of the end buttons is pressed:
                if (!trainReachedBottomStation.Value)
                {
                    trainMotor.Value = moveDirection;
                    trainReachedBottomStation.WaitFor(value: true, edgeOnly: false);
                    trainMotor.Value = 0.0f;
                }

                // Change direction for the next pass:
                moveDirection = -moveDirection;

                // Wait a bit before opening the doors:
                Thread.Sleep(waitAroundDoorOperationsInMs);

                // Open the door:
                doorMotor.Value = 1.0f;
                Thread.Sleep(waitForDoorsToMoveInMs);
                doorMotor.Value = 0.0f;

                // Let people step in and out, wait a bit:
                Thread.Sleep(waitWithOpenDoorsInMs);

                // Close the door:
                doorMotor.Value = -1.0f;
                Thread.Sleep(waitForDoorsToMoveInMs);
                doorMotor.Value = 0.0f;

                // Wait a bit before the train starts again:
                Thread.Sleep(waitAroundDoorOperationsInMs);
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// Runs a clock driven by a simple DC motor.
        /// </summary>
        /// <param name="motor">The motor to drive continuously.</param>
        /// <param name="minimumMotorSpeed">The minimum speed setting that causes the motor to turn. Speeds below this
        /// threshold may cause the motor to not turn at all.</param>
        /// <param name="initialSpeedGuess">A rough initial guess for a speed to try to reach the first cycle in time.
        /// </param>
        /// <param name="pulse">The input which pulses to measure the motor speed.</param>
        /// <param name="pulseDebounceMillisecondsAtFullSpeed">The time, in milliseconds, that shall be used as the
        /// debounce time for the <paramref name="pulse"/> input when the <paramref name="motor"/> runs at full speed.
        /// </param>
        /// <param name="pulseMonitor">An output to show the monitored pulse input.</param>
        /// <param name="idealSecondsPerCycle">The number of seconds for one pulse cycle which would give a perfectly
        /// accurate operation of the clock.</param>
        /// <remarks>The motor speed is constantly adapted to the measurement given by the pulse to realize the needed
        /// pulse times without cumulative errors, even if the motor changes its behaviour during the operation.
        /// </remarks>
        public static void Run(ISingleOutput motor,
                               float minimumMotorSpeed,
                               float initialSpeedGuess,
                               IBooleanInput pulse,
                               double idealSecondsPerCycle,
                               IBooleanInput runAtFullSpeedSwitch)
        {
            // Check parameters:
            if (motor == null)
            {
                throw new ArgumentNullException(nameof(motor));
            }
            if (minimumMotorSpeed <= 0f || minimumMotorSpeed >= 1f)
            {
                throw new ArgumentOutOfRangeException(nameof(minimumMotorSpeed));
            }
            if (initialSpeedGuess < minimumMotorSpeed || initialSpeedGuess > 1f)
            {
                throw new ArgumentOutOfRangeException(nameof(initialSpeedGuess));
            }
            if (pulse == null)
            {
                throw new ArgumentNullException(nameof(pulse));
            }
            if (idealSecondsPerCycle <= 0f)
            {
                throw new ArgumentOutOfRangeException(nameof(idealSecondsPerCycle));
            }


            // Run unit tests on the RunningAverageCalculator class:
            Console.WriteLine("Testing RunningAverageCalculator");
            RunningAverageCalculator.Test();
            Console.WriteLine("RunningAverageCalculator successfully tested");

            // An average calculator the motor output voltage (ranging from 0.0f to 1.0f) needed to read one cycle in
            // idealSecondsPerCycle seconds:
            var voltageForIdealCycleTime = new RunningAverageCalculator(10);

            // Add the initial guess of that voltage:
            voltageForIdealCycleTime.Add(initialSpeedGuess);

            // Give a short full speed pulse to the motor to get it surely running:
            motor.Value = 1.0f;
            System.Threading.Thread.Sleep(10);

            // Let the motor run until the pulse changes from false to true to initialize the position to a pulse
            // boundary:
            Console.WriteLine("Initializing to pulse position");
            motor.Value = initialSpeedGuess;
            pulse.WaitFor(true, true);

            // This is our starting point:
            var clockStartTime = DateTime.UtcNow;

            int      n  = 0;              // The number of cycles passed
            DateTime t0 = clockStartTime; // Ideal start of the running cycle
            DateTime a0 = t0;             // Actual start of the running cycle

            Console.WriteLine("Ideal seconds per cycle = " + idealSecondsPerCycle.ToString("N4"));
            Console.WriteLine("Running the clock at initial v = " + initialSpeedGuess.ToString("N4"));

            while (true)
            {
                if (runAtFullSpeedSwitch.Value)
                {
                    Console.WriteLine("Manually adjusting clock by running at full speed");

                    // Let the motor run at full speed to adjust the clock's time on the user's request:
                    float lastSpeed = motor.Value;
                    motor.Value = 1f;
                    runAtFullSpeedSwitch.WaitFor(false);

                    // Reinitialize:
                    Console.WriteLine("Initializing to pulse position");
                    motor.Value = lastSpeed;
                    pulse.WaitFor(true, true);
                    Console.WriteLine("Pulse reached");
                    n = 0;
                    clockStartTime = DateTime.UtcNow;
                    t0             = clockStartTime;
                    a0             = t0;
                }

                // Calculate the end of the current (and the beginning of the next) cylce:
                n++;
                DateTime t1   = clockStartTime.AddSeconds(idealSecondsPerCycle * n);
                double   t1a0 = (t1 - a0).TotalSeconds;

                // Wait for the next (debounced) pulse, telling us that we reached the end of the current cycle:
                DateTime a1;          // The actual end of the current cycle.
                double   a1a0;        // a1 - a0: The number of seconds between a0 and a1.
                int      bounces = 0; // The number of bounces the pulse contacts made

                do
                {
                    pulse.WaitFor(true, true);
                    a1   = DateTime.UtcNow;
                    a1a0 = (a1 - a0).TotalSeconds;
                    bounces++;
                } // Debounce by accepting the next pulse not earlier than at 70% of the wanted time interval:
                while (a1a0 < 0.7 * t1a0);

                // We may have missed one or more pulses due to mechanical errors in pulse detection.
                // Estimate the number of real cyles, rounding by adding 0.5 and casting to int (which truncates):
                int cycles = (int)((a1 - t1).TotalSeconds * motor.Value /
                                   (voltageForIdealCycleTime.Average * idealSecondsPerCycle)
                                   + 0.5)
                             + 1;

                if (cycles > 1)
                {
                    // We lost [cycles - 1] pulses. The worm turned multiple times until we got a contact.
                    // Adjust the counted pulses and the ideal target time for that number of pulses since the last
                    // contact:
                    n  = n + cycles - 1;
                    t1 = clockStartTime.AddSeconds(idealSecondsPerCycle * n);
                }

                // Take note of the current measurement's insight:
                voltageForIdealCycleTime.Add(motor.Value * a1a0 / (idealSecondsPerCycle * cycles));

                // Calculate the motor voltage needed to reach the next cycle pulse right in time t1 and
                // set the motor voltage to this value, taking the lower and upper bounds into account:

                DateTime t2 = clockStartTime.AddSeconds(idealSecondsPerCycle * (n + 1));

                motor.Value =
                    Math.Max(minimumMotorSpeed,
                             Math.Min(1.0f,
                                      (float)(voltageForIdealCycleTime.Average * idealSecondsPerCycle
                                              / (t2 - a1).TotalSeconds)));

                // Report to debugger:
                double diff = (a1 - t1).TotalSeconds;
                // Math.Abs(double) is not implemented on Netduiono 3:
                double absDiff = diff < 0.0 ? -diff : diff;

                Console.WriteLine(
                    "n = " + n.ToString("N0").PadLeft(8) +
                    " | bounces = " + bounces.ToString().PadLeft(3) +
                    " | cycles = " + cycles.ToString().PadLeft(2) +
                    " | vi = " + voltageForIdealCycleTime.Average.ToString("N4").PadLeft(6) +
                    " | t1 = " + t1.ToString("HH:mm:ss") +
                    " | a1 = " + a1.ToString("HH:mm:ss") +
                    " | " + (diff == 0.0 ? "exactly in time           " :
                             ((diff < 0.0 ? "early by " : " late by ") + absDiff.ToString("N4").PadLeft(7) + "s (" +
                              (absDiff * 100.0 / t1a0).ToString("N2").PadLeft(5) + "%)")) +
                    " | v = " + motor.Value.ToString("N4"));

                // The current cycle gets the passed one:
                t0 = t1;
                a0 = a1;
            }
        }