Super Kid
Published © GPL3+

Distance Sensor

This shows how to use the distance sensor.

BeginnerProtip6 minutes2,653
Distance Sensor

Things used in this project

Hardware components

Ultrasonic Sensor - HC-SR04 (Generic)
Ultrasonic Sensor - HC-SR04 (Generic)
×1
Raspberry Pi 2 Model B
Raspberry Pi 2 Model B
×1
Breadboard (generic)
Breadboard (generic)
×1
Resistor 1k ohm
Resistor 1k ohm
×1
Resistor 2.2k ohm
×1
Jumper wires (generic)
Jumper wires (generic)
×1

Software apps and online services

Windows 10 IoT Core
Microsoft Windows 10 IoT Core
Visual Studio 2015
Microsoft Visual Studio 2015

Story

Read more

Code

UltrasonicDistanceSensor.cs

C#
NOTE: This is a class, not the XAML code file
public class UltrasonicDistanceSensor
    {
        private readonly GpioPin _gpioPinTrig;
        // ReSharper disable once PrivateFieldCanBeConvertedToLocalVariable
        private readonly GpioPin _gpioPinEcho;
        private readonly Stopwatch _stopwatch;

        private double? _distance; 

        public UltrasonicDistanceSensor(int trigGpioPin, int echoGpioPin)
        {
            _stopwatch  = new Stopwatch();

            var gpio = GpioController.GetDefault();

            _gpioPinTrig = gpio.OpenPin(trigGpioPin);
            _gpioPinEcho = gpio.OpenPin(echoGpioPin);
            _gpioPinTrig.SetDriveMode(GpioPinDriveMode.Output);
            _gpioPinEcho.SetDriveMode(GpioPinDriveMode.Input);
            _gpioPinTrig.Write(GpioPinValue.Low);

            _gpioPinEcho.ValueChanged += GpioPinEcho_ValueChanged;
        }

        private void GpioPinEcho_ValueChanged(GpioPin sender, GpioPinValueChangedEventArgs args)
        {
            _distance = _stopwatch.ElapsedMilliseconds * 34.3 / 2.0;
            
        }

        public async Task<double> GetDistanceInCmAsync(int timeoutInMilliseconds)
        {
            _distance = null;
            try
            {
                _stopwatch.Reset();

                // turn on the pulse
                _gpioPinTrig.Write(GpioPinValue.High);
                await Task.Delay(TimeSpan.FromMilliseconds(10));
                _gpioPinTrig.Write(GpioPinValue.Low);

                _stopwatch.Start();
                for (var i = 0; i < timeoutInMilliseconds/100; i++)
                {
                    if (_distance.HasValue)
                        return _distance.Value;

                    await Task.Delay(TimeSpan.FromMilliseconds(100));
                }
            }
            finally
            {
                _stopwatch.Stop();
            }
            return double.MaxValue;
        }

    }

MainPage.xaml

HTML
<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <TextBox  HorizontalAlignment="Left" Height="305" Margin="10,275,0,0" TextWrapping="Wrap" FontSize="30" VerticalAlignment="Top" Name="ABC" Width="1900"/>
        <TextBox Name="Log" HorizontalAlignment="Left" Height="260" Margin="10,10,0,0" TextWrapping="Wrap" Text="" FontSize="30" VerticalAlignment="Top" Width="1900"/>
    </Grid>

Untitled file

C#
 public sealed partial class MainPage : Page
    {

        private BackgroundWorker _worker;
        private CoreDispatcher _dispatcher;

        private bool _finish;
        private UltrasonicDistanceSensor ultrasonicDistanceSensor = new UltrasonicDistanceSensor(23, 24);

        public MainPage()
        {
            InitializeComponent();

      
                Loaded += MainPage_Loaded;
       
            Unloaded += MainPage_Unloaded;
        }

        private void MainPage_Loaded(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            _dispatcher = CoreWindow.GetForCurrentThread().Dispatcher;

            _worker = new BackgroundWorker();
            _worker.DoWork += DoWork;
            _worker.RunWorkerAsync();
        }

        private void MainPage_Unloaded(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            _finish = true;
        }

        private async void DoWork(object sender, DoWorkEventArgs e)
        {
    
            
            while (!_finish)
            {
               
                await Task.Delay(50);

                var distance = await ultrasonicDistanceSensor.GetDistanceInCmAsync(1000);

                await WriteLog1($"Distance: {distance} cm ");
         
                if (distance > 35)
                {
                    continue;
                   

                }
                await WriteLog($"Obstacle found at {distance} cm or less.");
            }
        }

        private async Task WriteLog(string text)
        {
            await _dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
               Log.Text += $"{text} | ";
            
            });
        }

        private async Task WriteLog1(string text)
        {
            await _dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
     
                ABC.Text = $"{text} | ";
            });
        }
  }

Credits

Super Kid

Super Kid

1 project • 26 followers
I am building the project with IoT with Windows (Windows On Devices). Also I have a tag: Break your heart for the beginner.

Comments