Example #1
0
 /// <summary>
 /// Creates an instance.
 /// </summary>
 /// <param name="inputToDebounce">The input to debounce, for example a switch.</param>
 /// <param name="debounceMilliseconds">The number of milliseconds that value which was read from
 /// <paramref name="inputToDebounce"/> shall be returned unchanged by the resulting <see cref="IBooleanInput"/>,
 /// even if the source value changes (due to bouncing effects, say, on a mechanical switch).</param>
 public BooleanDebouncedInput(IBooleanInput inputToDebounce, int debounceMilliseconds)
 {
     this.InputToDebounce = inputToDebounce ?? throw new ArgumentNullException(nameof(inputToDebounce));
     if (debounceMilliseconds < 0)
     {
         throw new ArgumentOutOfRangeException(nameof(debounceMilliseconds));
     }
     _debounceMilliseconds = debounceMilliseconds;
 }
Example #2
0
        /// <summary>
        /// Pauses until an <see cref="IBooleanInput"/> returns a specified value, using polling.
        /// </summary>
        /// <param name="input">The input which shall be awaited.</param>
        /// <param name="value">The value that the input shall have before this method returns.</param>
        /// <remarks>
        /// This is a blocking method polling the <paramref name="input"/> value in short intervals.
        /// </remarks>
        public static void WaitFor(this IBooleanInput input, bool value)
        {
            if (input == null)
            {
                throw new ArgumentNullException(nameof(input));
            }

            // Wait for the input having the desired value.
            while (input.Value != value)
            {
                Thread.Sleep(1);
            }
        }
        public static void Run(IBooleanInput button, IBooleanOutput motor)
        {
            // Multithreading is simple:

            Thread thread = new Thread(() =>
            {
                while (true)
                {
                    motor.Value = button.Value;
                    System.Threading.Thread.Sleep(20);
                }
            });

            thread.Start();
        }
Example #4
0
        /// <summary>
        /// Pauses until an <see cref="IBooleanInput"/> changes its value and return the new value, using polling.
        /// </summary>
        /// <param name="input">The input which shall be awaited.</param>
        /// <returns>The new value of the input.</returns>
        public static bool WaitForChange(this IBooleanInput input)
        {
            if (input == null)
            {
                throw new ArgumentNullException(nameof(input));
            }

            bool oldValue = input.Value;
            bool newValue;

            while ((newValue = input.Value) == oldValue)
            {
                Thread.Sleep(1);
            }
            return(newValue);
        }
Example #5
0
        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));
            }

            // Control the lamp by the button, using polling:
            while (true)
            {
                lamp.Value = button.Value;
                Thread.Sleep(100); // Only to give you a chance to redeploy usung firmware as of 2018-04-08.
            }
        }
Example #6
0
        /// <summary>
        /// Pauses until an <see cref="IBooleanInput"/> returns a specified value, using polling, optionally on an edge.
        /// </summary>
        /// <param name="input">The input which shall be awaited.</param>
        /// <param name="value">The value that the input shall have before this method returns.</param>
        /// <param name="edgeOnly">If false, this method returns immediately if the desired <paramref name="value"/> is
        /// already present. If true, only a change from another value than <paramref name="value"/> to
        /// <paramref name="value"/> will cause the method to return.</param>
        /// <remarks>
        /// This is a blocking method polling the <paramref name="input"/> value in short intervals.
        /// </remarks>
        public static void WaitFor(this IBooleanInput input, bool value, bool edgeOnly)
        {
            if (input == null)
            {
                throw new ArgumentNullException(nameof(input));
            }

            // If we wait for an edge, wait for the input value be unequal to the desired value:
            if (edgeOnly)
            {
                while (input.Value == value)
                {
                    Thread.Sleep(1);
                }
            }

            // Now wait for the desired value:
            WaitFor(input, value);
        }
Example #7
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();
            }
        }
Example #8
0
 /// <summary>
 /// Creates a <see cref="BooleanInvertInput"/> using the specified source input.
 /// </summary>
 /// <param name="source">The input which shall be inverted.</param>
 /// <returns>The inverted input.</returns>
 /// <remarks>For instance, if you have an <see cref="IBooleanInput"/> object named "input", you can just code
 /// input.Invert() to get an inverted version of input.</remarks>
 public static IBooleanInput Invert(this IBooleanInput source)
 {
     return(new BooleanInvertInput(source));
 }
Example #9
0
 /// <summary>
 /// Creates an instance.
 /// </summary>
 /// <param name="source">The input to be converted.</param>
 public BooleanInvertInput(IBooleanInput source)
 {
     _source = source ?? throw new ArgumentNullException(nameof(source));
 }
 /// <summary>
 /// Creates a <see cref="BooleanMonitoredInput"/> which passes a copy of the read value of the source input to a
 /// tee target <see cref="IBooleanOutput"/> each time it gets read.
 /// </summary>
 /// <param name="sourceInput">The input to tee.</param>
 /// <param name="teeTarget">The output to receive the passed-through value of the
 /// <paramref name="sourceInput"/>.</param>
 /// <returns>The input which returns the <paramref name="sourceInput"/> value and at the same time sets the
 /// <paramref name="teeTarget"/> to that same value.</returns>
 public static BooleanMonitoredInput MonitoredTo(this IBooleanInput sourceInput, IBooleanOutput teeTarget)
 {
     return(new BooleanMonitoredInput(sourceInput, teeTarget));
 }
 /// <summary>
 /// Creates a <see cref="=BooleanDebouncedInput" which returnes a debounced version of a
 /// <see cref="IBooleanInput"/>.
 /// </summary>
 /// <param name="inputToDebounce">The input to debounce, for example a switch.</param>
 /// <param name="debounceMilliseconds">The number of milliseconds that value which was read from
 /// <paramref name="inputToDebounce"/> shall be returned unchanged by the resulting <see cref="IBooleanInput"/>,
 /// even if the source value changes (due to bouncing effects, say, on a mechanical switch).</param>
 /// <returns>The debounced input.</returns>
 public static BooleanDebouncedInput Debounced(this IBooleanInput inputToDebounce, int debounceMilliseconds)
 {
     return(new BooleanDebouncedInput(inputToDebounce, debounceMilliseconds));
 }
Example #12
0
 /// <summary>
 /// Creates an instance.
 /// </summary>
 /// <param name="sourceInput">The input to tee.</param>
 /// <param name="teeTarget">The output to receive the passed-through value of the
 /// <paramref name="sourceInput"/>.</param>
 public BooleanMonitoredInput(IBooleanInput sourceInput, IBooleanOutput teeTarget)
 {
     this.SourceInput = sourceInput ?? throw new ArgumentNullException(nameof(sourceInput));
     this.TeeTarget   = teeTarget ?? throw new ArgumentNullException(nameof(teeTarget));
 }
        /// <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 train1ReachedBottomStation,
                               IBooleanInput train2ReachedBottomStation,
                               ISingleOutput doorMotor,
                               IBooleanOutput redLight,
                               IBooleanOutput greenLight,
                               int waitForDoorsToMoveInMs,
                               int waitWithOpenDoorsInMs,
                               int waitAroundDoorOperationsInMs)
        {
            // Check arguments:

            if (trainMotor == null)
            {
                throw new ArgumentNullException(nameof(trainMotor));
            }
            if (train1ReachedBottomStation == null)
            {
                throw new ArgumentNullException(nameof(train1ReachedBottomStation));
            }
            if (train2ReachedBottomStation == null)
            {
                throw new ArgumentNullException(nameof(train2ReachedBottomStation));
            }
            if (doorMotor == null)
            {
                throw new ArgumentNullException(nameof(doorMotor));
            }
            if (redLight == null)
            {
                throw new ArgumentNullException(nameof(redLight));
            }
            if (greenLight == null)
            {
                throw new ArgumentNullException(nameof(greenLight));
            }
            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:

            bool moveDirection      = false;
            var  trainReachedBottom = new BooleanOrInput(train1ReachedBottomStation, train2ReachedBottomStation);

            while (true)
            {
                // Initialize lamps:
                redLight.Value   = true;
                greenLight.Value = false;

                // Move the train in the current direction until one of the end buttons is pressed:
                if (!(train1ReachedBottomStation.Value || train2ReachedBottomStation.Value))
                {
                    trainMotor.Value = moveDirection ? 1.0f : -1.0f;
                    trainReachedBottom.WaitFor(value: true, edgeOnly: false);
                    trainMotor.Value = 0.0f;
                }
                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:
                redLight.Value   = false;
                greenLight.Value = true;
                Thread.Sleep(waitWithOpenDoorsInMs);
                redLight.Value   = true;
                greenLight.Value = false;

                // 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);
            }
        }
        /// <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);
            }
        }
Example #15
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;
            }
        }