public MainPage() { this.InitializeComponent(); // Initialize Motor Driver Pins MotorDriver.InitializePins(MotorDriver.AvailableGpioPin.GpioPin_5, MotorDriver.AvailableGpioPin.GpioPin_6, MotorDriver.AvailableGpioPin.GpioPin_13, MotorDriver.AvailableGpioPin.GpioPin_26); // Initialize MyRecognizer and Load Grammar InitializeSpeechRecognizer(); // Initialize front distance sensor Sensor.UltrasonicDistanceSensor Front_DistanceSensor = new Sensor.UltrasonicDistanceSensor(Sensor.UltrasonicDistanceSensor.AvailableGpioPin.GpioPin_12, Sensor.UltrasonicDistanceSensor.AvailableGpioPin.GpioPin_16); // Initialize ObstacleDetection object Sensor.ObstacleDetection Front_ObstacleDetection = new Sensor.ObstacleDetection(Front_DistanceSensor); Front_ObstacleDetection.ObstacleDetected += Front_ObstacleDetection_ObstacleDetected; }
public ObstacleDetection(UltrasonicDistanceSensor _Sensor, int ScanResolutionInMs = 100) { // initialize CurrentDistance to zero double CurrentDistanceInCm = 0; // Create a separate Task to scan distance between obstacle and sensor Task.Factory.StartNew(async() => { // Loop infinity until the power is down while (true) { // Verify current distance ahead and raise event if MinDistance distance is breached if ((CurrentDistanceInCm = _Sensor.GetDistance()) <= MinDistance && CurrentState == DetectionState.Clear) { // Raise event only if it is not null if (ObstacleDetected != null) { ObstacleDetected(DetectionState.Detected, CurrentDistanceInCm); } // Set current state CurrentState = DetectionState.Detected; } else if (CurrentDistanceInCm > MinDistance && CurrentState == DetectionState.Detected) // Raise event if distance between object and sensor is greater than MinDistance { // Raise event only if it is not null if (ObstacleDetected != null) { ObstacleDetected(DetectionState.Clear, CurrentDistanceInCm); } // Set current state CurrentState = DetectionState.Clear; } // Wait for the next scan time await Task.Delay(ScanResolutionInMs); } }); }