Exemplo n.º 1
0
 private void PortDown_Changed(object sender, DigitalInputPortEventArgs e)
 {
     /*  graphics.Clear();
      * graphics.DrawText(0, 0, "D" + count++);
      * graphics.Show(); */
     //      snakeGame.Direction = SnakeDirection.Down;
 }
Exemplo n.º 2
0
 /// <summary>
 ///     Catch the PIR motion change interrupts and work out which interrupt should be raised.
 /// </summary>
 private void DigitalInputPortChanged(object sender, DigitalInputPortEventArgs e)
 {
     if (_digitalInputPort.State == true)
     {
         OnMotionDetected?.Invoke(this);
     }
 }
Exemplo n.º 3
0
        /// <summary>
        /// This event monitors the bPhase pin. It will raise an event on rotation if it is the second event fired (_processing = true) and bPhase triggered first (CounterClockwise rotation)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PhaseAPinChanged(object sender, DigitalInputPortEventArgs e)
        {
            // Lock the thread so protected variables are not modified while process
            lock (_lock)
            {
                if (_processing)
                {
                    if (_aTriggered)
                    {
                        //This is an invalid event because a-triggers can't toggle the processing flag
                        // However, this can be the start of a new triggering event!
                        // Don't change _processing or _aTriggered because if we are down this path it either means it is invalid or that b will soon trigger
                    }
                    else //Means b triggered first
                    {
                        OnRaiseRotationEvent(RotationDirection.CounterClockwise);
                        resetFlags(); // After successful flag!
                    }
                }
                else
                {
                    // toggle our processing flag
                    _processing = !_processing;
                }
                _aTriggered = true;
            }


            // to address issues where the flags have been reversed for whatever reason after time reset the flags
            new Task(() =>
            {
                Thread.Sleep(50); //all events should be within 50 ms of each other. This may cause issue if people are turning at super human speed
                resetFlags();
            }).Start();
        }
Exemplo n.º 4
0
        private void OnEchoPortChanged(object sender, DigitalInputPortEventArgs e)
        {
            if (e.Value == true)
            // if(_echoPort.State == true)
            {
                ///      Console.WriteLine("true");
                tickStart = DateTime.Now.Ticks;
                return;
            }

            //    Console.WriteLine("false");

            // Calculate Difference
            float elapsed = DateTime.Now.Ticks - tickStart;

            // Return elapsed ticks
            // x10 for ticks to micro sec
            // divide by 58 for cm (assume speed of sound is 340m/s)
            CurrentDistance = elapsed / 580f;

            //    if (CurrentDistance < MinimumDistance || CurrentDistance > MaximumDistance)
            //       CurrentDistance = -1;

            DistanceDetected?.Invoke(this, new DistanceEventArgs(CurrentDistance));
        }
Exemplo n.º 5
0
 /// <summary>
 /// This event monitors the bPhase pin. It will raise an event on rotation if it is the second event fired (_processing = true) and aPhase triggered first (clockwise rotation)
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void PhaseBPinChanged(object sender, DigitalInputPortEventArgs e)
 {
     lock (_lock)
     {
         if (_processing)
         {
             if (_aTriggered) //a triggered first
             {
                 OnRaiseRotationEvent(RotationDirection.Clockwise);
                 resetFlags(); // after successful flag!
             }
             else
             {
                 //This is an invalid path because if we are processing it means it is the second event fired. reset flags and return
                 // leave processing flag alone because if a now triggers it is a valid sequence
             }
             //ProcessRotationResults();
         }
         else
         {
             // toggle our processing flag - only toggle selectively to catch misfiring events
             _processing = !_processing;
         }
         _aTriggered = false;
     }
 }
Exemplo n.º 6
0
        private void OnEchoPortChanged(object sender, DigitalInputPortEventArgs e)
        {
            if (e.Value == true)
            // if(echoPort.State == true)
            {
                tickStart = DateTime.Now.Ticks;
                return;
            }

            //    Console.WriteLine("false");

            // Calculate Difference
            var elapsed = DateTime.Now.Ticks - tickStart;

            // Return elapsed ticks
            // x10 for ticks to micro sec
            // divide by 58 for cm (assume speed of sound is 340m/s)
            var curDis = elapsed / 580;

            CurrentDistance = curDis;

            //debug - remove
            Console.WriteLine($"{elapsed}, {curDis}, {CurrentDistance}, {DateTime.Now.Ticks}");

            //restore this before publishing to hide false results
            //    if (CurrentDistance < MinimumDistance || CurrentDistance > MaximumDistance)
            //       CurrentDistance = -1;

            DistanceDetected?.Invoke(this, new DistanceEventArgs(CurrentDistance));
        }
Exemplo n.º 7
0
        private void EchoChanged(object sender, DigitalInputPortEventArgs e)
        {
            //Console.WriteLine("value of echo:{0}", echo.State);
            if (!_IsStarted)
            {
                //Console.WriteLine("Start is false");
                return;
            }

            if (e.Value)
            {
                //Console.WriteLine("Echo value is true, reset duration");
                //duration = DateTime.Now.Ticks; // Start the clock.
                return;
            }

            // Echo got something back. We can calculate the duration.
            var endDate = DateTime.Now.Ticks;
            var delta   = endDate - duration;

            //Console.WriteLine("delta {0}", delta);
            CurrentDistance = delta / SpeedOfSoundFactor;
            DistanceDetected?.Invoke(this, new DistanceEventArgs(CurrentDistance));
            _IsStarted = false;
        }
Exemplo n.º 8
0
        /// <summary>
        ///     Sensor has generated an interrupt, work out what to do.
        /// </summary>
        private void InterruptChanged(object sender, DigitalInputPortEventArgs e)
        {
            var status = Status;

            if ((status & StatusBitsMask.ActivityDetected) != 0)
            {
                // AccelerationChanged(this, new SensorVectorEventArgs(lastNotifiedReading, currentReading));
            }
        }
Exemplo n.º 9
0
        void InputPortChanged(object sender, DigitalInputPortEventArgs e)
        {
            var time = DateTime.Now;

            // if it's the very first read, set the time and bail out
            if (_numberOfReads == 0 && _revolutionTimeStart == DateTime.MinValue)
            {
                //S.Console.WriteLine("First reading.");
                _revolutionTimeStart = time;
                _numberOfReads++;
                return;
            }

            // increment our count of magnet detections
            _numberOfReads++;

            // if we've made a full revolution
            if (_numberOfReads == NumberOfMagnets)
            {
                //S.Console.WriteLine("Viva La Revolucion!");
                // calculate how much time has elapsed since the start of the revolution
                var revolutionTime = time - _revolutionTimeStart;

                //S.Console.WriteLine("RevTime Milliseconds: " + revolutionTime.Milliseconds.ToString());

                if (revolutionTime.Milliseconds < 3)
                {
                    //S.Console.WriteLine("rev time < 3. Garbage, bailing.");
                    _numberOfReads       = 0;
                    _revolutionTimeStart = time;
                    return;
                }

                // calculate our rpms
                // RPSecond = 1000 / revTime.millis
                // PPMinute = RPSecond * 60
                _RPMs = ((float)1000 / (float)revolutionTime.Milliseconds) * (float)60;
                Console.WriteLine("RPMs: " + _RPMs);

                //if (revolutionTime.Milliseconds < 5) {
                //    S.Console.WriteLine("revolution time was < 5. garbage results.");
                //} else {
                //    S.Console.WriteLine("RPMs: " + _RPMs);
                //}


                // reset our number of reads and store our revolution time start
                _numberOfReads       = 0;
                _revolutionTimeStart = time;

                // if the change is enough, raise the event.
                if (Math.Abs(_lastNotifiedRPMs - _RPMs) > RPMChangeNotificationThreshold)
                {
                    OnRaiseRPMChanged();
                }
            }
        }
Exemplo n.º 10
0
        private void PortRight_Changed(object sender, DigitalInputPortEventArgs e)
        {
            /*    graphics.Clear();
             *  graphics.DrawText(0, 0, "R" + count++);
             *  graphics.Show(); */
            //   snakeGame.Direction = SnakeDirection.Right;

            breakoutGame.Right(breakoutGame.Paddle.Width);
        }
Exemplo n.º 11
0
        private void PhaseAPinChanged(object s, DigitalInputPortEventArgs e)
        {
            // Clear bit A bit
            uint new2LsBits = _dynamicOffset & 0x02;    // Save bit 2 (B)

            if (e.Value)
            {
                new2LsBits |= 0x01;                     // Set bit 1 (A)
            }
            FindDirection(new2LsBits);
        }
Exemplo n.º 12
0
 /// <summary>
 ///     Catch the PIR motion change interrupts and work out which interrupt should be raised.
 /// </summary>
 private void DigitalInputPortChanged(object sender, DigitalInputPortEventArgs e)
 {
     if (_digitalInputPort.State)
     {
         OnMotionStart?.Invoke(this);
     }
     else
     {
         OnMotionEnd?.Invoke(this);
     }
 }
Exemplo n.º 13
0
 /// <summary>
 ///     Interrupt from the MAG3110 conversion complete interrupt.
 /// </summary>
 private void DigitalInputPortChanged(object sender, DigitalInputPortEventArgs e)
 {
     if (OnReadingComplete != null)
     {
         Read();
         var readings = new SensorReading();
         readings.X = X;
         readings.Y = Y;
         readings.Z = Z;
         OnReadingComplete(readings);
     }
 }
Exemplo n.º 14
0
        private void OnStateChangedHandler(object sender, DigitalInputPortEventArgs e)
        {
            var port = sender as IDigitalInputPort;

            if (port == null)
            {
                Console.WriteLine($"sender is a {port.GetType().Name}");
            }
            else
            {
                Console.WriteLine($"{port.Pin.Name} state changed to {e.Value}");
            }
        }
Exemplo n.º 15
0
        /// <summary>
        ///     Sensor has generated an interrupt, work out what to do.
        /// </summary>
        private void InterruptChanged(object sender, DigitalInputPortEventArgs e)
        {
            var status = Status;

            if ((status & StatusBitsMask.ActivityDetected) != 0)
            {
                Vector lastNotifiedReading = new Vector(_lastX, _lastY, _lastZ);
                Vector currentReading      = new Vector(X, Y, Z);
                _lastX = X;
                _lastY = Y;
                _lastZ = Z;
                AccelerationChanged(this, new SensorVectorEventArgs(lastNotifiedReading, currentReading));
            }
        }
Exemplo n.º 16
0
        private void PhasePinChanged(object sender, DigitalInputPortEventArgs e)
        {
            //Console.WriteLine((!_processing ? "1st result: " : "2nd result: ") + "A{" + (APhasePin.Read() ? "1" : "0") + "}, " + "B{" + (BPhasePin.Read() ? "1" : "0") + "}");

            // the first time through (not processing) store the result in array slot 0.
            // second time through (is processing) store the result in array slot 1.
            _results[_processing ? 1 : 0].APhase = APhasePort.State;
            _results[_processing ? 1 : 0].BPhase = BPhasePort.State;

            // if this is the second result that we're reading, we should now have
            // enough information to know which way it's turning, so process the
            // gray code
            if (_processing)
            {
                ProcessRotationResults();
            }

            // toggle our processing flag
            _processing = !_processing;
        }
        private async void OnD06Changed(object sender, DigitalInputPortEventArgs args)
        {
            // The circuit had an led tied to Vcc an resister from the led to D06
            // and a push button from ground to D06. If the led has a low forward
            // drop pressing the button will cause the LED to blink.
            Console.WriteLine("D06 Interrupt");
            Console.WriteLine("D06 -> false");
            _d06.State = false;      // Becomes output & sets high
            await Task.Delay(2000);

            Console.WriteLine("D06 -> true");
            _d06.State = true;     // Still output & sets low
            await Task.Delay(2000);

            Console.WriteLine("D06 -> false");
            _d06.State = false;      // Still output & sets high
            await Task.Delay(2000);

            _d06.State = true;                        // Still output & sets low
            Console.WriteLine("D06 -> input");
            _d06.Direction = PortDirectionType.Input; // Return to input
        }
Exemplo n.º 18
0
 private void Button_Changed(object sender, DigitalInputPortEventArgs e)
 {
     Console.WriteLine("Button pressed");
     radio.SearchNextSilent();
     UpdateDisplay();
 }
Exemplo n.º 19
0
 private void Button_Changed(object sender, DigitalInputPortEventArgs e)
 {
     Console.WriteLine("Button pressed");
     isMetric = !isMetric;
 }
Exemplo n.º 20
0
 private void Input_Changed(object sender, DigitalInputPortEventArgs e)
 {
     Console.WriteLine($"Changed: {e.Value}, Time: {e.Time}");
 }
Exemplo n.º 21
0
 private void Input_Changed(object sender, DigitalInputPortEventArgs e)
 {
     Console.WriteLine("Changed: " + e.Value.ToString() + ", Time: " + e.Time.ToString());
 }
Exemplo n.º 22
0
 void OnChanged(DigitalInputPortEventArgs e)
 {
     PinEventChanged?.Invoke(this, e);
 }
Exemplo n.º 23
0
 private void InterruptPort_Changed(object sender, DigitalInputPortEventArgs e)
 {
     Console.WriteLine($"Motion detected: {e.Value}");
 }
Exemplo n.º 24
0
        private void InterruptGpioPin_ValueChanged(object sender, DigitalInputPortEventArgs args)
        {
            //TODO - Debug.WriteLine
            //Console.WriteLine("Interrupt Triggered: " + args.Value.ToString());

            if (!IsInitialized)
            {
                return;
            }

            if (!_enabled)
            {
                FlushReceiveBuffer();
                FlushTransferBuffer();
                return;
            }

            // Disable RX/TX
            IsEnabled = false;

            // Set PRX
            SetReceiveMode();

            // there are 3 rx pipes in rf module so 3 arrays should be enough to store incoming data
            // sometimes though more than 3 data packets are received somehow
            var payloads = new byte[6][];

            var  status           = GetStatus();
            byte payloadCount     = 0;
            var  payloadCorrupted = false;

            if (status.DataReady)
            {
                while (!status.RxEmpty)
                {
                    // Read payload size
                    var payloadLength = Execute(Commands.R_RX_PL_WID, 0x00, new byte[1]);

                    // this indicates corrupted data
                    if (payloadLength[1] > 32)
                    {
                        payloadCorrupted = true;

                        // Flush anything that remains in buffer
                        FlushReceiveBuffer();
                    }
                    else
                    {
                        if (payloadCount >= payloads.Length)
                        {
                            // TODO Debug.WriteLine
                            Console.WriteLine("Unexpected payloadCount value = " + payloadCount);
                            FlushReceiveBuffer();
                        }
                        else
                        {
                            // Read payload data
                            payloads[payloadCount] = Execute(Commands.R_RX_PAYLOAD, 0x00, new byte[payloadLength[1]]);
                            payloadCount++;
                        }
                    }

                    // Clear RX_DR bit
                    var result = Execute(Commands.W_REGISTER, Registers.STATUS, new[] { (byte)(1 << Bits.RX_DR) });
                    status.Update(result[0]);
                }
            }

            if (status.ResendLimitReached)
            {
                FlushTransferBuffer();

                // Clear MAX_RT bit in status register
                Execute(Commands.W_REGISTER, Registers.STATUS, new[] { (byte)(1 << Bits.MAX_RT) });
            }

            if (status.TxFull)
            {
                FlushTransferBuffer();
            }

            if (status.DataSent)
            {
                // Clear TX_DS bit in status register
                Execute(Commands.W_REGISTER, Registers.STATUS, new[] { (byte)(1 << Bits.TX_DS) });
                // TODO Debug.WriteLine("Data Sent!");
                Console.WriteLine("Data Sent!");
            }

            // Enable RX
            IsEnabled = true;

            if (payloadCorrupted)
            {
                // TODO Debug.WriteLine("Corrupted data received");
                Console.WriteLine("Corrupted data received");
            }
            else if (payloadCount > 0)
            {
                if (payloadCount > payloads.Length)
                {
                    // TODO Debug.WriteLine("Unexpected payloadCount value = " + payloadCount);
                    Console.WriteLine("Unexpected payloadCount value = " + payloadCount);
                }

                for (var i = 0; i < System.Math.Min(payloadCount, payloads.Length); i++)
                {
                    var payload = payloads[i];
                    var payloadWithoutCommand = new byte[payload.Length - 1];
                    Array.Copy(payload, 1, payloadWithoutCommand, 0, payload.Length - 1);
                    OnDataReceived(payloadWithoutCommand);
                }
            }
            else if (status.DataSent)
            {
                _transmitSuccessFlag.Set();
                OnTransmitSuccess();
            }
            else
            {
                _transmitFailedFlag.Set();
                OnTransmitFailed();
            }
        }
Exemplo n.º 25
0
 private void YellowButton_Changed(object sender, DigitalInputPortEventArgs e)
 {
 }
Exemplo n.º 26
0
 private void Button_Changed(object sender, DigitalInputPortEventArgs e)
 {
     // Console.WriteLine("Changed: " + e.Value.ToString() + ", Time: " + e.Time.ToString());
     Console.WriteLine("Event Changed => ToggleLed.");
     //ToggleLed(led);
 }
Exemplo n.º 27
0
 private static void OnSensorChanged(object sender, DigitalInputPortEventArgs e)
 {
     Console.WriteLine($"Motion {(e.Value ? "started" : "ended")}");
 }
Exemplo n.º 28
0
 /// <summary>
 ///     Process the interrupt generated by the TSL2561.
 /// </summary>
 private void InterruptPin_Changed(object sender, DigitalInputPortEventArgs e)
 {
     ReadingOutsideThresholdWindow?.Invoke(DateTime.Now);
 }
Exemplo n.º 29
0
 private void DigitalInputPort_Changed(object sender, DigitalInputPortEventArgs e)
 {
 }