Things used in this project

Hardware components:
51gzz5eu9pl. sx425
Ultrasonic Sensor - HC-SR04 (Generic)
×1
R8326274 01
Raspberry Pi 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

SmileBackPi
Easy
  • 80
  • 1

Work in progress

SmileBackPi is a simple Windows 10 IOT project that combines motion, video and Microsoft Cognitive services.

Pulse Train HAT USB to Serial/I2C Board
Easy
  • 49
  • 0

Full instructions

We've designed a PTHAT USB>Serial board, especially for people wanting to use it standalone that accommodates the popular FTDI 232 module.

[Tutorial] Control the Screen Brightness Automatically
Easy
  • 125
  • 2

Protip

This tutorial shows you how to control the screen brightness automatically. I use the LattePanda as a PC. Hope you like it.

MPU6050 Accelerometer on Windows 10 Raspberry 2
Easy
  • 155
  • 1

Protip

Using MPU6050 accelerometer data on Windows 10 Raspberry 2 to control model's roll and pitch with DirectX12XTK and ImGui.

Forgot Something: The Calliope-Remembrall will Remind You
Easy
  • 281
  • 2

Work in progress

This is an utterly useless project since this magical object is quite useless. Everybody forgets stuff, naturally.

Break your heart - IoT Project - IoT Blocky
Easy
  • 822
  • 4

Protip

Use this project to control the LEDs on the Raspberry Pi Sense HAT.

Add projectSign up / Login