Netduino home hardware projects downloads community

Jump to content


The Netduino forums have been replaced by new forums at community.wildernesslabs.co. This site has been preserved for archival purposes only and the ability to make new accounts or posts has been turned off.
Photo

Parallax Ping))) Ultrasonic Sensor


  • Please log in to reply
12 replies to this topic

#1 afulki

afulki

    Member

  • Members
  • PipPip
  • 13 posts
  • LocationNew York

Posted 21 April 2011 - 08:23 PM

Played around with the Ping))) sensor, came up with the following code. It uses a timer to initiate the sensor reads, and an event to report to the main application. Period and Enable / Disable are supported. I attached a zip with the project.

using System;
using System.Threading;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
using SecretLabs.NETMF.Hardware;
using SecretLabs.NETMF.Hardware.Netduino;

namespace ParallaxSensors
{
    /*******************************************************************
     * Reference the following DLLs
     *  - Microsoft.SPOT.Hardware
     *  - Microsoft.SPOT.Native
     *  - SecretLabs.NETMF.Hardware
     *  - SecretLabs.NETMF.Hardware.Netduino
     ******************************************************************/

    /// <summary>
    /// Holds the distance information for the event
    /// </summary>
    public class PingEventArgs
    {
        public PingEventArgs(int distance)
        {
            Distance = distance;
        }

        public int Distance { get; set; }
    }

    /// <summary>
    /// Implements a timer based distance measurement of distance (in cm) using the
    /// parallax Ping sensor
    /// 
    /// Example usage:
    /// public static void Main()
    /// {
    ///     Ping ping = new Ping(Pins.GPIO_PIN_D2, 1000, true);
    ///     ping.RangeEvent += new Ping.RangeTakenDelegate(ping_RangeEvent);
    ///
    ///     // Sleep forever!
    ///     Thread.Sleep(Timeout.Infinite);
    /// }
    ///
    /// static void ping_RangeEvent(object sender, PingEventArgs e)
    /// {
    ///     Debug.Print("Range: " +  e.Distance + " cm");
    /// }
    /// </summary>
    public class Ping
    {
        public delegate void RangeTakenDelegate(object sender, PingEventArgs e);
        public event RangeTakenDelegate RangeEvent;

        private TristatePort _port;
        private ExtendedTimer _timer;
        private int _period;
        private bool _enabled;

        /// <summary>
        /// Constructor: initializes the Ping class
        /// </summary>
        /// <param name="pin">which pin the sensor is connected to</param>
        /// <param name="period">time between pulses in millisec, minimum of 1000</param>
        /// <param name="enabled">if true, start pinging immediately, otherwise wait for enable</param>
        public Ping(Cpu.Pin pin, int period, bool enabled)
        {
            _port = new TristatePort(pin, false, false, ResistorModes.Disabled);

            // Initially set as disabled.
            _timer = new ExtendedTimer(TakeMeasurement, null, Timeout.Infinite, period);

            // Store the current period
            Period = period;

            // Set the enabled state
            Enabled = enabled;
        }

        /// <summary>
        /// Enable or disable the timer that triggers the read.
        /// </summary>
        public bool Enabled
        {
            get { return _enabled; }
            set
            {
                _enabled = value;

                _timer.Change((_enabled) ? 0 : Timeout.Infinite, Period);
            }
        }

        /// <summary>
        /// Set the period of pings, min is 1000ms
        /// </summary>
        public int Period
        {
            get { return _period; }
            set
            {
                _period = value;
                if (_period < 1000)
                    _period = 1000;

                // Set enabled to the current value to force update
                Enabled = _enabled;
            }
        }

        /// <summary>
        /// Get distance in cm
        /// </summary>
        /// <returns>distance in cm, based on wikipedia for dry air at 20C</returns>
        private int GetDistance()
        {

            // First we need to pulse the port from high to low.
            _port.Active = true; // Put port in write mode
            _port.Write(true);   // Pulse pin
            _port.Write(false);
            _port.Active = false;// Put port in read mode;    

            bool lineState = false;

            // Wait for the line to go high, for start of pulse.
            while (lineState == false)
                lineState = _port.Read();

            long startOfPulseAt = System.DateTime.Now.Ticks;      // Save start ticks.

            // Wait for line to go low.
            while (lineState)
                lineState = _port.Read();

            long endOfPulse = System.DateTime.Now.Ticks;          // Save end ticks. 

            int ticks = (int)(endOfPulse - startOfPulseAt);

            return ticks / 580;
        }

        /// <summary>
        /// Initiates the pulse, and triggers the event
        /// </summary>
        /// <param name="stateInfo"></param>
        private void TakeMeasurement(Object stateInfo)
        {
            int distance = GetDistance();

            if (RangeEvent != null)
            {
                RangeEvent(this, new PingEventArgs(distance));
            }
        }
    }
}

Attached Files

  • Attached File  Ping.zip   3.02KB   127 downloads


#2 afulki

afulki

    Member

  • Members
  • PipPip
  • 13 posts
  • LocationNew York

Posted 02 May 2011 - 05:43 PM

More example code using the above class, traffic lights based on distance.

    public class Program
    {
        private static OutputPort _yellow = new OutputPort(Pins.GPIO_PIN_D6, false);
        private static OutputPort _red = new OutputPort(Pins.GPIO_PIN_D5, false);
        private static OutputPort _green = new OutputPort(Pins.GPIO_PIN_D7, false);

        public static void Main()
        {
            Ping ping = new Ping(Pins.GPIO_PIN_D2, 1000, true);
            ping.RangeEvent += new Ping.RangeTakenDelegate(ping_RangeEvent);

            // Sleep forever!
            Thread.Sleep(Timeout.Infinite);
        }

        static void ping_RangeEvent(object sender, PingEventArgs e)
        {
            Debug.Print("Range: " +  e.Distance + " cm");

            _yellow.Write(e.Distance > 50 && e.Distance < 100);
            _red.Write(e.Distance < 50);
            _green.Write(e.Distance > 100);
        }
    }



#3 ryan_sorensen

ryan_sorensen

    New Member

  • Members
  • Pip
  • 4 posts

Posted 29 October 2011 - 06:21 AM

Thanks for the sample! It worked perfectly on the first try. Now what fun things can i do with this??

#4 Johan

Johan

    Member

  • Members
  • PipPip
  • 10 posts

Posted 01 November 2011 - 07:47 AM

Thanks for this example. I'm new at Netduino and C# and even I could read the code clearly. Hopefully more people will take the time to add there references to there code. For me that takes some time to find out every time :-)

#5 bmccutch

bmccutch

    New Member

  • Members
  • Pip
  • 5 posts

Posted 24 November 2011 - 03:21 AM

Looks pretty cool

#6 Crash_Overload

Crash_Overload

    New Member

  • Members
  • Pip
  • 7 posts
  • LocationTexas

Posted 29 December 2012 - 02:24 PM

Hello,

 

i cant seem to get mine to work when i run the application it just sites there.



#7 Crash_Overload

Crash_Overload

    New Member

  • Members
  • Pip
  • 7 posts
  • LocationTexas

Posted 29 December 2012 - 02:36 PM

hahaha nevermind wrong pin



#8 rubenhak

rubenhak

    Member

  • Members
  • PipPip
  • 10 posts

Posted 10 February 2013 - 10:20 AM

First of all thanks for sharing this piece of code. When the using the parallax ping alone this piece of code works fine. But sometimes when using it together with servos and motors it gets stuck the the while loop. Is this something anybody else experienced? I'm using external 5v power source for all components. Also, is there a way to make this utility work in an asynchronous way where instead of waiting for signal in a loop I could get an interrupt and process it.

#9 zee

zee

    Advanced Member

  • Members
  • PipPipPip
  • 47 posts

Posted 09 April 2013 - 02:17 AM

Hi Afulki,

 

There are no errors in the coding but i received this error when running the program.

 

'The project must have either an output type of Console Application', or an output type of Class Library and the start action set to a valid .NET MicroFramework application'

 

What does the error means? Your guidance are really appreciated :) Thanks..



#10 JerseyTechGuy

JerseyTechGuy

    Advanced Member

  • Members
  • PipPipPip
  • 870 posts

Posted 09 April 2013 - 02:32 AM

Hi Afulki,

 

There are no errors in the coding but i received this error when running the program.

 

'The project must have either an output type of Console Application', or an output type of Class Library and the start action set to a valid .NET MicroFramework application'

 

What does the error means? Your guidance are really appreciated :) Thanks..

This means your project type and start type are incorrect.  If you are deploying to a netduino it should be set as a console application.



#11 zee

zee

    Advanced Member

  • Members
  • PipPipPip
  • 47 posts

Posted 09 April 2013 - 04:05 AM

Hi Dave,

 

I have changed the output type, and it exit the program by itself immediately. The Main() method is suppose to comment out or uncomment?

If i comment out, there is an error saying does not contain static Main. If i uncomment, it exit the program.



#12 JerseyTechGuy

JerseyTechGuy

    Advanced Member

  • Members
  • PipPipPip
  • 870 posts

Posted 09 April 2013 - 11:21 AM

Hi Dave,

 

I have changed the output type, and it exit the program by itself immediately. The Main() method is suppose to comment out or uncomment?

If i comment out, there is an error saying does not contain static Main. If i uncomment, it exit the program.

 

The main method contains the code that will run on the Netduino. Without it you're program will not work.

 

If your code is like Afulki's code above it should stay in the while loop forever.  Perhaps it is throwing an error and stopping the execution of the code.  You may need to debug and step through the code to see what is happening.



#13 chevi99

chevi99

    Member

  • Members
  • PipPip
  • 19 posts

Posted 22 June 2014 - 09:21 PM

hi can i get the library class for mb 1260 sensor from maxbotix






0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users

home    hardware    projects    downloads    community    where to buy    contact Copyright © 2016 Wilderness Labs Inc.  |  Legal   |   CC BY-SA
This webpage is licensed under a Creative Commons Attribution-ShareAlike License.