Things used in this project

Hardware components:
51gzz5eu9pl. sx425
Ultrasonic Sensor - HC-SR04 (Generic)
×1
R8326274 01
Raspberry Pi 2 Model B
×1
12002 04
Breadboard (generic)
×1
Mfr 25frf52 1k sml
Resistor 1k ohm
×1
Resistor 2.2k ohm
×1
11026 02
Jumper wires (generic)
×1
Software apps and online services:
10
Microsoft Windows 10 IoT Core
Vs2015logo
Microsoft Visual Studio 2015

Code

UltrasonicDistanceSensor.csC#
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.xamlHTML
<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 fileC#
 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

315922854b8b9d601de0d0238ddaf323
Super Kid

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

Contact

Replications

Did you replicate this project? Share it!

I made one

Love this project? Think it could be improved? Tell us what you think!

Give feedback

Comments

Similar projects you might like

New MATRIX Creator Weather App on Eclipse Day
Easy
  • 13
  • 2

Full instructions

In celebration of Eclipse Day we have made this app to tell you what the weather is outside so you know if you can see the eclipse.

Chicken Coop Livestream
Easy
  • 2,881
  • 11

Full instructions

We have two chickens, and their coop is located at the back of the garden. I decided to build a Pi-based streaming device to check on them.

Test Your Internet Speed Using a Raspberry Pi + Ubidots
Easy
  • 453
  • 6

Protip

Use your Raspberry Pi to measure any internet connection speed with Ubidots.

How to interface Arduino with RaspberryPi
Easy
  • 165
  • 2

Protip

In this I have shown how to send data from temperature sensor which is connected to Arduino and send data to Rpi database.

Raspberry Pi Shutdown / Restart Button
Easy
  • 5,419
  • 20

Full instructions

Building an installation project? Shut down or reboot your project safely, without a keyboard or SSH!

DIY Raspberry Pi Indoor Outdoor Webcam
Easy
  • 1,689
  • 6

Full instructions

Ever want to monitor your home but don't want to buy a $100 1080p webcam? Well I did, and you can too!

Sign up / LoginProjectsPlatformsTopicsContestsLiveAppsBetaFree StoreBlog