Hardware components | ||||||
| × | 1 | ||||
| × | 1 | ||||
| × | 1 | ||||
| × | 1 | ||||
| × | 1 | ||||
| × | 1 | ||||
Software apps and online services | ||||||
| ||||||
|
Using the Raspberry Pi with the distance sensor.
Why we need a 1k + 2.2k resistor?Because the voltage of the HC-SR04 is 5V while the Raspberry Pi is 3.3V. This can harm your Pi.
How to calculate:
- R1=1000ohm R2=2000ohm
- Vin = 5V(Sensor)
- Vout = 5 * (2000/(1000 + 2000)) = 3.3V.
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;
}
}
<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>
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} | ";
});
}
}
Comments