Need Help on changing netduino code to Spider Code

Put a Thread.Sleep(100) inside your while(true) loop.

I think you have pins reversed. First is the trig pin.

Hi Architect this is the code file in Program.Generated.cs


//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by the Gadgeteer Designer.
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

using Gadgeteer;
using GTM = Gadgeteer.Modules;
using System;
using System.Collections;
using System.Threading;
using Microsoft.SPOT;
using Microsoft.SPOT.Presentation;
using Microsoft.SPOT.Presentation.Controls;
using Microsoft.SPOT.Presentation.Media;
using Microsoft.SPOT.Touch;
using Gadgeteer.Networking;
using GT = Gadgeteer;
using Gadgeteer.Modules.GHIElectronics;
using Microsoft.SPOT.Hardware;
using GHI.Premium.Hardware;
using HC;

namespace GadgeteerApp1
{
    public partial class Program : Gadgeteer.Program
    {
        // GTM.Module definitions
        Gadgeteer.Modules.GHIElectronics.Extender extender;
        Gadgeteer.Modules.GHIElectronics.UsbClientDP usbClientDP;
        Gadgeteer.Modules.GHIElectronics.MotorControllerL298 motorControllerL298;

        public static void Main()
        {
            //Important to initialize the Mainboard first
            Mainboard = new GHIElectronics.Gadgeteer.FEZSpider();			

            Program program = new Program();
            program.InitializeModules();
            program.ProgramStarted();
            program.Run(); // Starts Dispatcher
            HC_SR04 sensor = new HC_SR04(EMX.Pin.IO8, EMX.Pin.IO45);


            while (true)
            {
                long ticks = sensor.Ping();
                Thread.Sleep(100);
                if (ticks > 0L)
                {
                    double inches = sensor.TicksToInches(ticks);
                }
            }
        }

        void ProgramStarted()
        {
            /*******************************************************************************************
            Modules added in the Program.gadgeteer designer view are used by typing 
            their name followed by a period, e.g.  button.  or  camera.
            
            Many modules generate useful events. Type +=<tab><tab> to add a handler to an event, e.g.:
                button.ButtonPressed +=<tab><tab>
            
            If you want to do something periodically, use a GT.Timer and handle its Tick event, e.g.:
                GT.Timer timer = new GT.Timer(1000); // every second (1000ms)
                timer.Tick +=<tab><tab>
                timer.Start();
            *******************************************************************************************/


            // Use Debug.Print to show messages in Visual Studio's "Output" window during debugging.
            Debug.Print("Program Started");
        }

        private void InitializeModules()
        {   
            // Initialize GTM.Modules and event handlers here.		
            usbClientDP = new GTM.GHIElectronics.UsbClientDP(1);
		
            extender = new GTM.GHIElectronics.Extender(10);
		
            motorControllerL298 = new GTM.GHIElectronics.MotorControllerL298(11);

        }
    }
}

This is the Program.cs file.

using System;
using System.Collections;
using System.Threading;
using Microsoft.SPOT;
using Microsoft.SPOT.Presentation;
using Microsoft.SPOT.Presentation.Controls;
using Microsoft.SPOT.Presentation.Media;
using Microsoft.SPOT.Touch;
using Gadgeteer.Networking;
using GT = Gadgeteer;
using GTM = Gadgeteer.Modules;
using Gadgeteer.Modules.GHIElectronics;
using Microsoft.SPOT.Hardware;
using Gadgeteer;
using GHI.Premium.Hardware;


//using SecretLabs.NETMF.Hardware;
//using SecretLabs.NETMF.Hardware.Netduino;

namespace HC
{
    public class HC_SR04
    {
        private OutputPort portOut;
        private InterruptPort interIn;
        private long beginTick;
        private long endTick;
        private long minTicks;  // System latency, subtracted off ticks to find actual sound travel time
        private double inchConversion;
        private double version;
        //Socket _socket;




       

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="pinTrig">Netduino pin connected to the HC-SR04 Trig pin</param>
        /// <param name="pinEcho">Netduino pin connected to the HC-SR04 Echo pin</param>
        public HC_SR04(Cpu.Pin pinTrig, Cpu.Pin pinEcho)
       // public HC_SR04(EMX.Pin pinTrig, EMX.Pin pinEcho)

        
       
        {
   
            portOut = new OutputPort(pinTrig, false);
            interIn = new InterruptPort(pinEcho, false, Port.ResistorMode.Disabled, Port.InterruptMode.InterruptEdgeLow);
            interIn.OnInterrupt += new NativeEventHandler(interIn_OnInterrupt);
            minTicks = 6200L;
            inchConversion = 1440.0;
            version = 1.1;
        }

        /// <summary>
        /// Returns the library version number
        /// </summary>
        public double Version
        {
            get
            {
                return version;
            }
        }

        /// <summary>
        /// Trigger a sensor reading
        /// Convert ticks to distance using TicksToInches below
        /// </summary>
        /// <returns>Number of ticks it takes to get back sonic pulse</returns>
        public long Ping()
        {
            // Reset Sensor
            portOut.Write(true);
            Thread.Sleep(1);

            // Start Clock
            endTick = 0L;
            beginTick = System.DateTime.Now.Ticks;
            // Trigger Sonic Pulse
            portOut.Write(false);

            // Wait 1/20 second (this could be set as a variable instead of constant)
            Thread.Sleep(50);

            if (endTick > 0L)
            {
                // Calculate Difference
                long elapsed = endTick - beginTick;

                // Subtract out fixed overhead (interrupt lag, etc.)
                elapsed -= minTicks;
                if (elapsed < 0L)
                {
                    elapsed = 0L;
                }

                // Return elapsed ticks
                return elapsed;
            }

            // Sonic pulse wasn't detected within 1/20 second
            return -1L;
        }

        /// <summary>
        /// This interrupt will trigger when detector receives back reflected sonic pulse       
        /// </summary>
        /// <param name="data1">Not used</param>
        /// <param name="data2">Not used</param>
        /// <param name="time">Transfer to endTick to calculated sound pulse travel time</param>
        void interIn_OnInterrupt(uint data1, uint data2, DateTime time)
        {
            // Save the ticks when pulse was received back
            endTick = time.Ticks;
        }

        /// <summary>
        /// Convert ticks to inches
        /// </summary>
        /// <param name="ticks"></param>
        /// <returns></returns>
        public double TicksToInches(long ticks)
        {
            return (double)ticks / inchConversion;
        }

        /// <summary>
        /// The ticks to inches conversion factor
        /// </summary>
        public double InchCoversionFactor
        {
            get
            {
                return inchConversion;
            }
            set
            {
                inchConversion = value;
            }
        }

        /// <summary>
        /// The system latency (minimum number of ticks)
        /// This number will be subtracted off to find actual sound travel time
        /// </summary>
        public long LatencyTicks
        {
            get
            {
                return minTicks;
            }
            set
            {
                minTicks = value;
            }
        }
    }

    public class Program
    {
        //public static void Main()
        //{
        //    //HC_SR04 sensor = new HC_SR04(Pins.GPIO_PIN_D6, Pins.GPIO_PIN_D7);
           
        //}
    }
}

But the output is like this. What is the fault.

Using mainboard GHI Electronics FEZSpider version 1.0
Program Started
The thread ‘’ (0x3) has exited with code 0 (0x0).

Ok, you are mixing Gadgeteer and non-Gadgeteer approaches. Use one or the other.

Which Means ? Please Advice . I’m Stucked with the code…

Ok

  1. start new Gadgeteer project and don’t modify Program.Generated.cs at all.

  2. Add your modules and connect them in the designer

  3. Move HC_SR04 class into its own cs file.

ProgramStarted method should be in Program.cs now.

  1. declare a class variable for HC_SR04 inside Program.cs

  2. Instantiate it in ProgramStarted

  3. Create Timer and take measurements inside Timer Tick handler.

Hi Architect ,
I have modified the code as you said but the out is the same … :frowning:

using System;
using System.Collections;
using System.Threading;
using Microsoft.SPOT;
using Microsoft.SPOT.Presentation;
using Microsoft.SPOT.Presentation.Controls;
using Microsoft.SPOT.Presentation.Media;
using Microsoft.SPOT.Touch;

using Gadgeteer.Networking;
using GT = Gadgeteer;
using GTM = Gadgeteer.Modules;
using Gadgeteer.Modules.GHIElectronics;
using GHI.Premium.Hardware;
using Gadgeteer.Interfaces;
using HC_SR04;

namespace archi
{
    public partial class Program
    {
        HC_SR04.HC_SR04 sensor;
        
        // This method is run when the mainboard is powered up or reset.   
        void ProgramStarted()
        {
           

            /*******************************************************************************************
            Modules added in the Program.gadgeteer designer view are used by typing 
            their name followed by a period, e.g.  button.  or  camera.
            
            Many modules generate useful events. Type +=<tab><tab> to add a handler to an event, e.g.:
                button.ButtonPressed +=<tab><tab>
            
            If you want to do something periodically, use a GT.Timer and handle its Tick event, e.g.:
                GT.Timer timer = new GT.Timer(1000); // every second (1000ms)
                timer.Tick +=<tab><tab>
                timer.Start();
            *******************************************************************************************/


            // Use Debug.Print to show messages in Visual Studio's "Output" window during debugging.

            Debug.Print("Program Started");
            sensor = new HC_SR04.HC_SR04(EMX.Pin.IO8, EMX.Pin.IO45);
            
            GT.Timer timer = new GT.Timer(1000);

           timer.Tick += new GT.Timer.TickEventHandler(timer_Tick);

            }

        void timer_Tick(GT.Timer timer)
        {
            while (true)
            {
                long ticks = sensor.Ping();
                Thread.Sleep(100);
                if (ticks > 0L)
                {
                    double inches = sensor.TicksToInches(ticks);
                }
            }
        }


        

    }
}

The first thing I would try to determine is if an interrupt is occurring. if not, there is a wiring issue.

If the interrupt is occurring, I would print out the timing values and make sure the numbers make sense.

There is a value for overhead. Is this number appropriate for the MF device you are using? If this
number is too big, it could make the ping results go bad. Try setting to zero. First get it working
and then calibrate.

Don’t do while(true) loop inside the Timer handler. And make it class variable. Something like this:


    public partial class Program
    {
        GT.Timer timer = new GT.Timer(1000);
        HC_SR04.HC_SR04 sensor;

        // This method is run when the mainboard is powered up or reset.   
        void ProgramStarted()
        {
            sensor = new HC_SR04.HC_SR04(EMX.Pin.IO8, EMX.Pin.IO45);
            timer.Tick += new GT.Timer.TickEventHandler(timer_Tick);
            timer.Start();

            // Use Debug.Print to show messages in Visual Studio's "Output" window during debugging.
            Debug.Print("Program Started");
        }

        void timer_Tick(GT.Timer timer)
        {
            long ticks = sensor.Ping();
            if (ticks > 0L)
            {
                double inches = sensor.TicksToInches(ticks);
                Debug.Print(inches.ToString());
            }
            
        }
    }

Thanks Architect You are Awesome :slight_smile:

You are welcome!

To be more safe in case pin out changes or you move it to a different socket I would use something like this when creating the sensor:

Socket socket = Socket.GetSocket(10, true, null, null);
sensor = new HC_SR04(socket.CpuPins[5], socket.CpuPins[3]);