private void buttonPin_ValueChanged(GpioPin sender, GpioPinValueChangedEventArgs e)
        {
            //// toggle the state of the LED every time the button is pressed
            //if (e.Edge == GpioPinEdge.FallingEdge)
            //{
            //    ledPinValue = (ledPinValue == GpioPinValue.Low) ?
            //        GpioPinValue.High : GpioPinValue.Low;
            //    ledPin.Write(ledPinValue);
            //}

            // need to invoke UI updates on the UI thread because this event
            // handler gets invoked on a separate thread.
            var task = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => {
                if (buttonPin.Read() == GpioPinValue.High)
                {
                    ledPinValue     = GpioPinValue.High;
                    ledEllipse.Fill = grayBrush;
                    ledPin.Write(ledPinValue);
                    GpioStatus.Text = "No Mouse...";
                    SendMessageToIoTHubAsync(1);
                }
                if (buttonPin.Read() == GpioPinValue.Low)
                {
                    ledPinValue     = GpioPinValue.Low;
                    ledEllipse.Fill = redBrush;
                    ledPin.Write(ledPinValue);
                    GpioStatus.Text = "Dead Mouse...";
                    SendMessageToIoTHubAsync(2);
                }
            });
        }
Exemple #2
0
        private void Timer_Tick(object sender, object e)
        {
            // Toggle the existing pin value.
            //currentValue = (currentValue == GpioPinValue.High) ? GpioPinValue.Low : GpioPinValue.High;

            Debug.WriteLine("Checking for flame");

            var task = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                string CurrentPinValue = aoPin.Read().ToString();
                Debug.WriteLine("ao: " + CurrentPinValue);

                if (aoPin.Read().Equals(GpioPinValue.High))
                {
                    Debug.WriteLine("Flame detected");

                    SendSensorValue("FlameSensor", 1, this.ViewModel.DeviceId);

                    //    if (viewModel.IsSending)
                    //        viewModel.SendSensorValue("FlameSensor", 1);

                    //_timer = new Timer(new TimerCallback((x) =>
                    //{
                    //    MainPageViewModel viewModel = ((MainPageViewModel)x);

                    //    if (viewModel.IsSending)
                    //        viewModel.SendSensorValue("FlameSensor", 1);

                    //}), this.ViewModel, 1000, 3000);

                    //TODO: add in notification to UI
                    //TODO: instead of checking every 5 seconds, check all the time but only send request every 5 seconds
                }
            });
        }
Exemple #3
0
        private List <Tuple <byte, double> > RecordCode()
        {
            var pulseList     = new List <Tuple <byte, double> >();
            var value         = true;
            var numOnes       = 0;
            var previousValue = false;

            while (value)
            {
                value = _inputPin.Read();
            }

            var stopwatch = Stopwatch.StartNew();

            while (numOnes < MaxAcCommandLength)
            {
                if (value != previousValue)
                {
                    var pulseLength = stopwatch.Elapsed;
                    stopwatch.Restart();
                    pulseList.Add(new Tuple <byte, double>(previousValue ? (byte)1 : (byte)0, pulseLength.TotalMilliseconds * 1000));
                }

                numOnes = value ? numOnes + 1 : 0;

                previousValue = value;
                value         = _inputPin.Read();
            }
            stopwatch.Stop();

            return(pulseList);
        }
        private void Timer_Tick(object sender, object e)
        {
            distance.Text = "1";
            pinTrigger.Write(GpioPinValue.High);
            distance.Text = "3";
            Task.Delay(TimeSpan.FromMilliseconds(0.01)).Wait();

            pinTrigger.Write(GpioPinValue.Low);
            Task.Delay(TimeSpan.FromMilliseconds(100)).Wait();

            distance.Text = "4";
            sw.Start();
            distance.Text = "444";
            distance.Text = pinEcho.Read().ToString();
            while (pinEcho.Read() == GpioPinValue.Low)
            {
                distance.Text = "no";
            }

            while (pinEcho.Read() == GpioPinValue.High)
            {
                distance.Text = "nonono";
            }
            sw.Stop();
            distance.Text = "no";

            var elapsed   = sw.Elapsed.TotalSeconds;
            var distance1 = elapsed * 34000;

            distance1    /= 2;
            distance.Text = "Distance: " + distance1 + " cm";
        }
Exemple #5
0
        public static void Main()
        {
            try
            {
                // Init the displays
                InitDisplays();

                // Some blinky first
                _led = GpioController.GetDefault().OpenPin(Gpio.UserLed);
                _led.SetDriveMode(GpioPinDriveMode.Output);

                // Create a timer with a second jump
                _blinker = 0;
                _counter = 0;
                _timer   = new Timer(Tick, null, 0, 1000);

                // The mandatory heartbeat
                for (; ;)
                {
                    _led.Write(_led.Read() == GpioPinValue.High ? GpioPinValue.Low : GpioPinValue.High);
                    Thread.Sleep(1000);
                }
            }
            catch (Exception ex)
            {
                // Do whatever please you with the exception caught
                Console.WriteLine(ex.ToString());
                for (; ;)
                {
                    _led.Write(_led.Read() == GpioPinValue.High ? GpioPinValue.Low : GpioPinValue.High);
                    Thread.Sleep(250);
                }
            }
        }
        private async void fuktighetMetode()
        {
            var controller = GpioController.GetDefault();

            if (controller != null)
            {
                _pin = controller.OpenPin(LED);
                _pin.SetDriveMode(GpioPinDriveMode.Input);
                while (true)
                {
                    if (_pin.Read().ToString() == "Low")
                    {
                        LampeFuktighet.Fill = new SolidColorBrush(Colors.Red);
                        tb_fuktighet.Text   = "High moisture levels!";
                    }

                    if (_pin.Read().ToString() == "High")
                    {
                        LampeFuktighet.Fill = new SolidColorBrush(Colors.Black);
                        tb_fuktighet.Text   = "";
                    }

                    await Task.Delay(10);
                }
            }
            else
            {
                System.Diagnostics.Debug.WriteLine("Target device does not have GPIO pins.");
            }
        }
Exemple #7
0
 private void phi_ink1_pin_ValueChanged(GpioPin sender, GpioPinValueChangedEventArgs e)
 {
     try
     {
         if (phi_ink1_pin.Read() == GpioPinValue.High)
         {
             //if (phi_ink2_pressed == true)
             //{
             //    if (phi_ink2_pin.Read() == GpioPinValue.High)
             //        phi_act--;
             //    else
             //        phi_act++;
             //    actual.setPhi(phi_act);
             //}
             if (phi_right_pin.Read() == GpioPinValue.High)
             {
                 phi_act--;
             }
             else if (phi_left_pin.Read() == GpioPinValue.High)
             {
                 phi_act++;
             }
             actual.setPhi(phi_act);
             phi_ink2_pressed = false;
         }
     }
     catch
     {
         StopAll();
         throw;
     }
 }
Exemple #8
0
        private static double PulseIn(GpioPin pin, GpioPinValue value, int timeout)
        {
            StaticComponents.StopWatch.Restart();

            // Wait for pulse
            while (StaticComponents.StopWatch.ElapsedMilliseconds < timeout && pin.Read() != value)
            {
            }

            if (StaticComponents.StopWatch.ElapsedMilliseconds >= timeout)
            {
                StaticComponents.StopWatch.Stop();
                return(0);
            }
            StaticComponents.StopWatch.Restart();

            // Wait for pulse end
            while (StaticComponents.StopWatch.ElapsedMilliseconds < timeout && pin.Read() == value)
            {
            }

            StaticComponents.StopWatch.Stop();

            return(StaticComponents.StopWatch.ElapsedMilliseconds < timeout ? StaticComponents.StopWatch.Elapsed.TotalSeconds : 0);
        }
Exemple #9
0
 private void z_ink1_pin_ValueChanged(GpioPin sender, GpioPinValueChangedEventArgs e)
 {
     try
     {
         if (z_ink1_pin.Read() == GpioPinValue.High)
         {
             //if (z_ink2_pressed == true)
             //{
             //    if (z_ink2_pin.Read() == GpioPinValue.High)
             //        z_act--;
             //    else
             //        z_act++;
             //    actual.setZ(z_act);
             //}
             if (z_up_pin.Read() == GpioPinValue.High)
             {
                 z_act--;
             }
             else if (z_down_pin.Read() == GpioPinValue.High)
             {
                 z_act++;
             }
             actual.setZ(z_act);
             z_ink2_pressed = false;
         }
     }
     catch
     {
         StopAll();
         throw;
     }
 }
Exemple #10
0
        public static void Main()
        {
            try
            {
                // Initate the one and only on board Led
                Console.WriteLine("Program started");

                _led = GpioController.GetDefault().OpenPin(Gpio.UserLed);
                _led.SetDriveMode(GpioPinDriveMode.Output);
                _led.Write(GpioPinValue.Low);

                for (; ;)
                {
                    _led.Write(_led.Read() == GpioPinValue.Low ? GpioPinValue.High : GpioPinValue.Low);
                    Thread.Sleep(100);
                }
            }
            catch (Exception ex)
            {
                // Don't leave thread
                Console.WriteLine(ex.ToString());

                for (; ;)
                {
                    _led.Write(_led.Read() == GpioPinValue.Low ? GpioPinValue.High : GpioPinValue.Low);
                    Thread.Sleep(100);
                }
            }
        }
Exemple #11
0
        public static void Main()
        {
            try
            {
                Console.WriteLine("\rHello world of nanoFramework!\r");

                // Setup the signal LED
                InitGpio();

                // Setup the serial communication with the sensor
                InitSensor();

                // And watch your console output
                for (; ;)
                {
                    _ledUser.Write(_ledUser.Read() == GpioPinValue.Low ? GpioPinValue.High : GpioPinValue.Low);
                    Thread.Sleep(500);
                }
            }
            catch (Exception ex)
            {
                // Don't leave thread
                Console.WriteLine(ex.ToString());

                for (; ;)
                {
                    _ledUser.Write(_ledUser.Read() == GpioPinValue.Low ? GpioPinValue.High : GpioPinValue.Low);
                    Thread.Sleep(100);
                }
            }
        }
Exemple #12
0
 //conversion / communication with ADC initialization
 public void EdgeDetCLKOnValueChanged(GpioPin sender, GpioPinValueChangedEventArgs args)
 {
     if (args.Edge.Equals(GpioPinEdge.FallingEdge))
     {
         if (initProgress == 0b00000000)
         {
             SYNC2.Write(GpioPinValue.High);
             initProgress |= 0b00000011;
         }
         else if (initProgress == 0b00000011)
         {
             SYNC2.Write(GpioPinValue.Low);
             if (FSO2.Read().Equals(GpioPinValue.Low))
             {
                 initProgress = 0; //startOver
             }
             if (FSO2.Read().Equals(GpioPinValue.High))
             {
                 CLK2.ValueChanged -= EdgeDetCLKOnValueChanged; //listen to edges on CLK
                 FSO2.ValueChanged += EdgeDetFSOOnValueChanged; //listen to edges on FSO
                 initProgress      |= 0b00001100;
             }
         }
     }
 }
Exemple #13
0
 public bool StepOrario(int s)
 {
     if (_endStopOr.Read() == LOW)
     {
         return(false);          //Esce se arrivato a fine corsa
     }
     for (int i = 0; i < s; i++) //Effettua i passi richiesti
     {
         if (_endStopOr.Read() == LOW)
         {
             if (s != 1)
             {
                 InvokeWriteLog("Gone clockwise for " + s + " steps and reached endline");
             }
             return(false); //Esce se arrivato a fine corsa
         }
         _fase++;           //Passa alla fase successiva
         _fase = _fase % 4; //Rotazione fasi 0-1-2-3
         AttivaFase();
     }
     //Toglie alimentazione alle fasi
     Folle();
     //Thread.Sleep(3);
     if (s != 1)
     {
         InvokeWriteLog("Gone clockwise for " + s + " steps and NOT reached endline");
     }
     return(true); //Non è arrivato al fine corsa
 }
Exemple #14
0
        /// <summary>
        ///     Reads the temperature from the TempHum4 Click.
        /// </summary>
        /// <param name="source">The <see cref="TemperatureSources" /> to read the Temperature from.</param>
        /// <returns>The temperature measured in the unit specified in the TemperatureUnits property. Defaults to °C.</returns>
        /// <exception cref="InvalidOperationException">
        ///     an InvalidOperationException will be thrown if attempting to read
        ///     <see cref="TemperatureSources.Object" /> as this module does not support object measurement.
        /// </exception>
        /// <example>
        ///     Example usage:
        ///     <code language="C#">
        /// Debug.WriteLine("Temperature - " + _sensor.ReadTemperature());
        /// </code>
        /// </example>
        public Single ReadTemperature(TemperatureSources source = TemperatureSources.Ambient)
        {
            if (source == TemperatureSources.Object)
            {
                throw new InvalidOperationException(
                          "Object temperature measurement not supported by the TempHum11 Click");
            }

            if (AcquisitionMode == AcquisitionModes.Sequential)
            {
                throw new ApplicationException(
                          "You cannot read temperature independantly while Acquisition Mode is set for sequential access. Use the ReadSensor method instead.");
            }

            WriteByte(TempRegister);

            while (_dataReadyPin.Read() == GpioPinValue.High)
            {
            }

            Byte[] readBuffer = ReadBytes(2);

            Single temperature = (Single)((readBuffer[0] << 8) / 65536.0 * 165.0 - 40.0);

            return(ConvertToScale(temperature));
        }
Exemple #15
0
        private void pirPin_ValueChanged(GpioPin sender, GpioPinValueChangedEventArgs e)
        {
            // toggle the state of the LED every time the button is pressed
            // puvodni kod
            //if (e.Edge == GpioPinEdge.FallingEdge)
            //{
            //    ledPinValue = (ledPinValue == GpioPinValue.Low) ?
            //        GpioPinValue.High : GpioPinValue.Low;
            //    ledPin.Write(ledPinValue);
            //}

            //Debug.WriteLine(e.Edge.ToString());

            if (e.Edge == GpioPinEdge.RisingEdge)
            {
                Debug.WriteLine("PIR-rising");
                Debug.WriteLine(pirPin.Read().ToString());

                led2Pin.Write(GpioPinValue.Low);
            }
            else
            {
                Debug.WriteLine("PIR-falling");
                Debug.WriteLine(pirPin.Read().ToString());

                led2Pin.Write(GpioPinValue.High);
            }
        }
        public static double GetTimeUntilNextEdge(GpioPin pin, GpioPinValue edgeToWaitFor, int maximumTimeToWaitInMilliseconds)
        {
            var t = Task.Run(() =>
            {
                stopWatch.Reset();

                while (pin.Read() != edgeToWaitFor)
                {
                }
                ;

                stopWatch.Start();

                while (pin.Read() == edgeToWaitFor)
                {
                }
                ;

                stopWatch.Stop();

                return(stopWatch.Elapsed.TotalSeconds);
            });

            var isCompleted = t.Wait(TimeSpan.FromMilliseconds(maximumTimeToWaitInMilliseconds));

            if (isCompleted)
            {
                return(t.Result);
            }
            else
            {
                return(0.0d);
            }
        }
Exemple #17
0
        private double PulseIn(GpioPin pin, GpioPinValue value, int timeout)
        {
            sw.Restart();

            // Wait for pulse
            while (sw.ElapsedMilliseconds < timeout && pin.Read() != value)
            {
            }

            if (sw.ElapsedMilliseconds >= timeout)
            {
                sw.Stop();
                return(0);
            }
            sw.Restart();

            // Wait for pulse end
            while (sw.ElapsedMilliseconds < timeout && pin.Read() == value)
            {
            }

            sw.Stop();

            return(sw.ElapsedMilliseconds < timeout ? sw.Elapsed.TotalMilliseconds : 0);
        }
Exemple #18
0
    double distanceV1(int max_wait_time)
    {
        stopwatch.Reset();
        trigPin.Write(GpioPinValue.High);
        eventSlim.Wait(TimeSpan.FromMilliseconds(0.01));
        trigPin.Write(GpioPinValue.Low);
        while (echoPin.Read() == GpioPinValue.Low)
        {
        }
        task = Task <double> .Factory.StartNew(() =>
        {
            stopwatch.Start();
            cts.CancelAfter(max_wait_time);
            while (echoPin.Read() == GpioPinValue.High)
            {
            }
            stopwatch.Stop();
            return(stopwatch.Elapsed.TotalSeconds * 343.2);
        }, ct);

        task.Wait(ct);
        if (task.IsCanceled)
        {
            return(-1);
        }
        return(task.Result);
    }
        private async Task SetupButton()
        {
            var controller = GpioController.GetDefault();

            _button = controller.OpenPin(_buttonPin);
            _button.SetDriveMode(GpioPinDriveMode.InputPullUp);

            GpioPinValue oldPinValue = _button.Read();
            GpioPinValue newPinValue;
            int          counter = 0;

            while (true)
            {
                newPinValue = _button.Read();
                if (newPinValue != oldPinValue)
                {
                    counter++;
                    if (newPinValue == GpioPinValue.Low)
                    {
                        await TelemetrySendLoop(true);
                    }
                    oldPinValue = newPinValue;
                }
            }
        }
        private void ReadSignalFromSensor()
        {
            long         startMeasurement = GetMicroSeconds();
            long         endMeasurement   = startMeasurement + ReceivingDataBitsTimeoutMilliSeconds * 1000;
            GpioPinValue currentValue     = _dhtPin.Read();
            GpioPinValue newValue         = currentValue;
            int          receivedSignals  = 0;
            long         now = 0;

            do
            {
                now      = GetMicroSeconds();
                newValue = _dhtPin.Read();

                if (newValue != currentValue)
                {
                    // changeDetected
                    _receivedSignal.Add(new Edge
                    {
                        MicrosFromStart = (int)(now - startMeasurement),
                        NewValue        = newValue
                    });

                    currentValue = newValue;
                    receivedSignals++;
                }
            } while (now < endMeasurement && receivedSignals < 82);
            // just wait this 10 millis to receive the full data signal or stop when 82 changes are detected (1 ack bit and 40 data bits)
        }
Exemple #21
0
        private double PulseIn(GpioPin pin, GpioPinValue value, ushort timeout)
        {
            var sw         = new Stopwatch();
            var sw_timeout = new Stopwatch();

            sw_timeout.Start();

            // Wait for pulse
            while (pin.Read() != value)
            {
                if (sw_timeout.ElapsedMilliseconds > timeout)
                {
                    return(3.5);
                }
            }
            sw.Start();

            // Wait for pulse end
            while (pin.Read() == value)
            {
                if (sw_timeout.ElapsedMilliseconds > timeout)
                {
                    return(3.4);
                }
            }
            sw.Stop();

            return(sw.Elapsed.TotalSeconds);
        }
        public async Task <double> GetDistanceInCmAsync(int timeoutInMilliseconds)
        {
            return(await Task.Run(() =>
            {
                double distance = double.MaxValue;
                // turn on the pulse
                _gpioPinTrig.Write(GpioPinValue.High);
                Task.Delay(TimeSpan.FromTicks(100)).Wait();
                _gpioPinTrig.Write(GpioPinValue.Low);

                if (SpinWait.SpinUntil(
                        () => { return _gpioPinEcho.Read() != GpioPinValue.Low; },
                        timeoutInMilliseconds))
                {
                    var stopwatch = Stopwatch.StartNew();
                    while (stopwatch.ElapsedMilliseconds < timeoutInMilliseconds && _gpioPinEcho.Read() == GpioPinValue.High)
                    {
                        distance = stopwatch.Elapsed.TotalSeconds * 17150;
                    }
                    stopwatch.Stop();
                    return distance;
                }
                throw new TimeoutException("Could not read from sensor");
            }));
        }
Exemple #23
0
        private double PulseIn(GpioPin pin, GpioPinValue value, ushort timeout)
        {
            var sw        = new Stopwatch();
            var swTimeout = new Stopwatch();

            swTimeout.Start();

            // Waits for pulse.
            while (pin.Read() != value)
            {
                if (swTimeout.ElapsedMilliseconds > timeout)
                {
                    return(prevTime);
                }
                //return 3.5;
            }

            sw.Start();

            // Waits for pulse end.
            while (pin.Read() == value)
            {
                if (swTimeout.ElapsedMilliseconds > timeout)
                {
                    return(prevTime);
                }
                //return 3.4;
            }

            sw.Stop();

            return(sw.Elapsed.TotalSeconds);
        }
 private void Experiment()
 {
     while (true)
     {
         // exit if both buttons pressed
         if (button1.Read() == GpioPinValue.Low && button2.Read() == GpioPinValue.Low)
         {
             break;
         }
         // button1 pressed -> turn LED_1 ON
         else if (button1.Read() == GpioPinValue.Low && button2.Read() == GpioPinValue.High)
         {
             led1.Write(GpioPinValue.Low);
             led2.Write(GpioPinValue.High);
         }
         // button2 pressed -> turn LED_2 ON
         else if (button1.Read() == GpioPinValue.High && button2.Read() == GpioPinValue.Low)
         {
             led1.Write(GpioPinValue.High);
             led2.Write(GpioPinValue.Low);
         }
         // no button pressed
         else
         {
             led1.Write(GpioPinValue.High);
             led2.Write(GpioPinValue.High);
         }
     }
 }
Exemple #25
0
        public static decimal MeasureDistance()
        {
            GpioPin triggerPin = Pi.Gpio[TriggerPin];
            GpioPin echoPin    = Pi.Gpio[EchoPin];

            triggerPin.PinMode = GpioPinDriveMode.Output;
            echoPin.PinMode    = GpioPinDriveMode.Input;

            triggerPin.Write(false);
            Pi.Timing.SleepMicroseconds(500000);
            triggerPin.Write(true);
            Pi.Timing.SleepMicroseconds(10);
            triggerPin.Write(false);

            var stopwatch = Stopwatch.StartNew();

            //Loop until the Echo pin is taken high (==1)
            while (!echoPin.Read() && stopwatch.ElapsedMilliseconds < 500)
            {
                ;
            }
            stopwatch.Restart();
            // Loop until it goes low again
            while (echoPin.Read() && stopwatch.ElapsedMilliseconds < 500)
            {
                ;
            }
            stopwatch.Stop();
            var distance = CalulateDistance((decimal)stopwatch.Elapsed.TotalSeconds);

            return(distance);
        }
Exemple #26
0
        public double GetDistance()
        {
            ManualResetEvent mre = new ManualResetEvent(false);

            mre.WaitOne(500);
            Stopwatch pulseLength = new Stopwatch();

            //Send pulse
            TriggerPin.Write(GpioPinValue.High);
            mre.WaitOne(TimeSpan.FromMilliseconds(0.01));
            TriggerPin.Write(GpioPinValue.Low);

            while (EchoPin.Read() == GpioPinValue.Low)
            {
            }
            pulseLength.Start();

            while (EchoPin.Read() == GpioPinValue.High)
            {
            }
            pulseLength.Stop();

            TimeSpan timeBetween = pulseLength.Elapsed;

            Debug.WriteLine(timeBetween.ToString());
            double distance = timeBetween.TotalSeconds * 17000;

            return(distance);
        }
Exemple #27
0
        private double PulseIn()
        {
            var sw         = new Stopwatch();
            var sw_timeout = new Stopwatch();
            var timeout    = 500;

            sw_timeout.Start();

            // Wait for pulse
            while (_inPin.Read() != GpioPinValue.High)
            {
                if (sw_timeout.ElapsedMilliseconds > timeout)
                {
                    return(3.5);
                }
            }

            sw.Start();

            // Wait for pulse end
            while (_inPin.Read() == GpioPinValue.High)
            {
                if (sw_timeout.ElapsedMilliseconds > timeout)
                {
                    return(3.4);
                }
            }

            sw.Stop();

            return(sw.Elapsed.TotalSeconds);
        }
            static void ThreadTimer()
            {
                while (true)
                {
                    Thread.Sleep(50);

                    if (buttonCenter == null)
                    {
                        continue;
                    }

                    if (buttonCenter.Read() == GpioPinValue.Low)
                    {
                        if (isButtonCenterPressed == false)
                        {
                            isButtonCenterPressed = true;
                        }
                    }

                    if (buttonCenter.Read() == GpioPinValue.High)
                    {
                        if (isButtonCenterPressed == true)
                        {
                            isButtonCenterPressed = false;

                            ButtonCenter_ValueChanged(buttonCenter, null);
                        }
                    }
                }
            }
Exemple #29
0
        private long GetDistanceHelper()
        {
            var mre = new ManualResetEventSlim(false);

            long start        = 0;
            long microseconds = 0;
            long time         = 0;
            long distance     = 0;
            var  sw           = new Stopwatch();

            //Send a 10µs pulse to start the measurement
            Trigger.Write(GpioPinValue.High);
            mre.Wait(TimeSpan.FromTicks(100));
            Trigger.Write(GpioPinValue.Low);

            int error = 0;

            while (Echo.Read() != GpioPinValue.High)
            {
                error++;
                if (error > 1000)
                {
                    break;
                }
                mre.Wait(TimeSpan.FromTicks(0));
            }

            start = DateTime.Now.Ticks;
            sw.Start();

            while (Echo.Read() == GpioPinValue.High)
            {
                mre.Wait(TimeSpan.FromTicks(0));
            }

            time = (DateTime.Now.Ticks - start);
            sw.Stop();
            microseconds = sw.Elapsed.Ticks / TicksPerMicrosecond;

            distance  = (microseconds / 58);
            distance += 2;

            if (distance < MAX_DISTANCE)
            {
                if (distance >= MIN_DISTANCE)
                {
                    return(distance);
                }
                else
                {
                    return(MinFlag);
                }
            }
            else
            {
                return(MaxFlag);
            }
        }
Exemple #30
0
        public short CollectFrame()
        {
            ushort theFrame        = 0;
            ushort collectProgress = 0x8002; // 0x8001;

            SCLKedge = 1;
            FSOedge  = 0;

            while (collectProgress != 0)
            {
                if (collectProgress == 0x8002 && FSO2.Read().Equals(GpioPinValue.High))
                {
                    collectProgress = 0x8001;
                }
                if (collectProgress == 0x8001 && FSO2.Read().Equals(GpioPinValue.Low))
                {
                    collectProgress = 0x8000;
                }
                if (0 < collectProgress && collectProgress <= 0x8000)
                {
                    if (SCLK2.Read().Equals(GpioPinValue.Low) && SCLKedge == 1)
                    {
                        SCLKedge = 0; //falling SCLK edge
                        if (DOUT2.Read().Equals(GpioPinValue.High))
                        {
                            theFrame |= collectProgress; //if data line is high, set current bit high
                        }
                        collectProgress >>= 1;           //shift to next bit (less significant)
                    }
                    if (SCLK2.Read().Equals(GpioPinValue.High) && SCLKedge == 0)
                    {
                        SCLKedge = 1; //rising SCLK edge
                    }
                }



                //if (FSOedge == F_ && collectProgress == 0x8001)
                //{
                //    FSOedge = 0; //restore edgeDet marker
                //    collectProgress = 0x8000;
                //    SCLK2.ValueChanged += EdgeDetSCLKOnValueChanged; //listen to edges on SCLK
                //    SCLKedge = 0;
                //}
                //if (SCLKedge == F_ && collectProgress < 0x8001)
                //{
                //    SCLKedge = 0;
                //    if (DOUT2.Read().Equals(GpioPinValue.High))
                //    {
                //        theFrame |= collectProgress; //if data line is high, set current bit high
                //    }
                //    collectProgress >>= 1; //shift to next bit (less significant)
                //}
            }

            //SCLK2.ValueChanged -= EdgeDetSCLKOnValueChanged;
            return((short)theFrame);
        }