Zhang happy Windows 10 IoT Development Notes: HC-SR04 Ultrasonic Ranging module, iothc-sr04
HC-SR04 with IO-triggered ranging. The following describes how to use Windows 10 IoT Core.
The project runs on Raspberry Pi 2/3 and uses C # for encoding.
1. Prepare
HC-SR04 X 1
Raspberry Pi 2/3 × 1
Dubang line with a public head × 4
2. wired
Vcc-5 V
Gnd-GND
Trig-GPIO 17-Pin 11
Echo-GPIO 27-Pin 13
3. Code
GitHub: https://github.com/ZhangGaoxing/windows-iot-demo/tree/master/HC_SR04Demo
Add a C # code file HCSR04.cs to the project, copy and paste the following code, and do not forget to add references.Windows IoT Extensions for the UWP
using System.Diagnostics;using System.Threading.Tasks;using Windows.Devices.Gpio;namespace HC_SR04Demo{ class HCSR04 { private int sensorTrig; private int sensorEcho; private GpioPin pinTrig; private GpioPin pinEcho; Stopwatch time = new Stopwatch(); /// <summary> /// Constructor /// </summary> /// <param name="trig">Trig Pin</param> /// <param name="echo">Echo Pin</param> public HCSR04(int trig, int echo) { sensorTrig = trig; sensorEcho = echo; } /// <summary> /// Initialize the sensor /// </summary> public void Initialize() { var gpio = GpioController.GetDefault(); pinTrig = gpio.OpenPin(sensorTrig); pinEcho = gpio.OpenPin(sensorEcho); pinTrig.SetDriveMode(GpioPinDriveMode.Output); pinEcho.SetDriveMode(GpioPinDriveMode.Input); pinTrig.Write(GpioPinValue.Low); } /// <summary> /// Read data from the sensor /// </summary> /// <returns>A double type distance data</returns> public async Task<double> ReadAsync() { double result; pinTrig.Write(GpioPinValue.High); await Task.Delay(10); pinTrig.Write(GpioPinValue.Low); while (pinEcho.Read() == GpioPinValue.Low) { } time.Restart(); while (pinEcho.Read() == GpioPinValue.High) { } time.Stop(); result = (time.Elapsed.TotalSeconds * 34000) / 2; return result; } /// <summary> /// Cleanup /// </summary> public void Dispose() { pinTrig.Dispose(); pinEcho.Dispose(); } }}
4. How to Use
The first step is to call the constructor to instantiate HCSR04. input the connection values of Trig and Echo.
Step 2 call Initialize () to Initialize the device
Step 3: Call ReadAsync () to read data and return a value of the double type.
Call Dispose () when you need to disable the device ()
For details, see GitHub.