The code works well and the variations are on a few millimeters, but I would like to know what I could do to eliminate, or at least reduce as much as possible those variations.
Here is my code (I am using a cheap HC-SR04 sensor)
using System; using System.Threading; using Microsoft.SPOT; using Microsoft.SPOT.Hardware; using SecretLabs.NETMF.Hardware; using SecretLabs.NETMF.Hardware.Netduino; // Written by BG on July the 25th 2011 to test the HC-SR04 sensor namespace Netduino_UltraSonicSensor { public class Program { private static int ticks; private static InterruptPort EchoPin = new InterruptPort(Pins.GPIO_PIN_D10, true, Port.ResistorMode.Disabled, Port.InterruptMode.InterruptEdgeBoth); private static OutputPort TriggerPin = new OutputPort(Pins.GPIO_PIN_D12, false); public static void Main() { EchoPin.OnInterrupt += new NativeEventHandler(port_OnInterrupt); EchoPin.DisableInterrupt(); while (true) { Distance(); //Debug.Print("distance = " + myDistance + " mm."); Thread.Sleep(1000); } } public static void Distance() { EchoPin.EnableInterrupt(); TriggerPin.Write(false); Thread.Sleep(2); TriggerPin.Write(true); Thread.Sleep(10); TriggerPin.Write(false); Thread.Sleep(2); } private static void port_OnInterrupt(uint port, uint state, DateTime time) { if (state == 0) // falling edge, end of pulse { int pulseWidth = (int) time.Ticks - ticks; // valid for 20°C //int pulseWidthMilliSeconds = pulseWidth * 10 / 582; //valid for 24°C int pulseWidthMilliSeconds = (pulseWidth * 10 / (int)578.29); Debug.Print("Distance = " + pulseWidthMilliSeconds.ToString() + " millimètres." ); } else { ticks = (int)time.Ticks; } EchoPin.ClearInterrupt(); } } }
and here are my readings:
I use 5v as it does not work in 3.3v, and I am a total beginner in electronics, so if there is a proper way to stabilize the 5 volts alimentation, I am all ears...
Thanks for any help.