element14 Community
element14 Community
    Register Log In
  • Site
  • Search
  • Log In Register
  • About Us
  • Community Hub
    Community Hub
    • What's New on element14
    • Feedback and Support
    • Benefits of Membership
    • Personal Blogs
    • Members Area
    • Achievement Levels
  • Learn
    Learn
    • Ask an Expert
    • eBooks
    • element14 presents
    • Learning Center
    • Tech Spotlight
    • STEM Academy
    • Webinars, Training and Events
    • Learning Groups
  • Technologies
    Technologies
    • 3D Printing
    • FPGA
    • Industrial Automation
    • Internet of Things
    • Power & Energy
    • Sensors
    • Technology Groups
  • Challenges & Projects
    Challenges & Projects
    • Design Challenges
    • element14 presents Projects
    • Project14
    • Arduino Projects
    • Raspberry Pi Projects
    • Project Groups
  • Products
    Products
    • Arduino
    • Avnet Boards Community
    • Dev Tools
    • Manufacturers
    • Multicomp Pro
    • Product Groups
    • Raspberry Pi
    • RoadTests & Reviews
  • Store
    Store
    • Visit Your Store
    • Choose another store...
      • Europe
      •  Austria (German)
      •  Belgium (Dutch, French)
      •  Bulgaria (Bulgarian)
      •  Czech Republic (Czech)
      •  Denmark (Danish)
      •  Estonia (Estonian)
      •  Finland (Finnish)
      •  France (French)
      •  Germany (German)
      •  Hungary (Hungarian)
      •  Ireland
      •  Israel
      •  Italy (Italian)
      •  Latvia (Latvian)
      •  
      •  Lithuania (Lithuanian)
      •  Netherlands (Dutch)
      •  Norway (Norwegian)
      •  Poland (Polish)
      •  Portugal (Portuguese)
      •  Romania (Romanian)
      •  Russia (Russian)
      •  Slovakia (Slovak)
      •  Slovenia (Slovenian)
      •  Spain (Spanish)
      •  Sweden (Swedish)
      •  Switzerland(German, French)
      •  Turkey (Turkish)
      •  United Kingdom
      • Asia Pacific
      •  Australia
      •  China
      •  Hong Kong
      •  India
      •  Korea (Korean)
      •  Malaysia
      •  New Zealand
      •  Philippines
      •  Singapore
      •  Taiwan
      •  Thailand (Thai)
      • Americas
      •  Brazil (Portuguese)
      •  Canada
      •  Mexico (Spanish)
      •  United States
      Can't find the country/region you're looking for? Visit our export site or find a local distributor.
  • Translate
  • Profile
  • Settings
Arduino
  • Products
  • More
Arduino
Arduino Forum Coding question for setup of Ultrasonic sensor (HC-SR04) and Buzzer - Arduino Uno
  • Blog
  • Forum
  • Documents
  • Quiz
  • Events
  • Polls
  • Files
  • Members
  • Mentions
  • Sub-Groups
  • Tags
  • More
  • Cancel
  • New
Join Arduino to participate - click to join for free!
Actions
  • Share
  • More
  • Cancel
Forum Thread Details
  • State Not Answered
  • Replies 3 replies
  • Subscribers 392 subscribers
  • Views 829 views
  • Users 0 members are here
  • coding
  • ultrasonic sensor
  • arduino uno
  • buzzer
Related

Coding question for setup of Ultrasonic sensor (HC-SR04) and Buzzer - Arduino Uno

Former Member
Former Member over 9 years ago

 

 

I am relatively new to Arduino so I know the basics however I am not the best at coding. My problem is that I am not sure about the coding for the following setup: I am using a Ultrasonic Sensor (HC-SR04) and a piezo buzzer. I want to be able to move my hand towards the sensor and away from the sensor and in doing this the buzzer will produce notes which will increase and decrease in pitch relative to my hand movement. (e.g. when my hand moves closer to the sensor the notes rise in pitch and when my hand moves away the notes decrease in pitch) I would greatly appreciate any feedback or help as I am quite stuck and it is for a college project!

  • Sign in to reply
  • Cancel
  • clem57
    0 clem57 over 9 years ago

         You only need to supply a short 10uS pulse to the trigger input to start the ranging, and then the module will send out an 8 cycle burst of ultrasound at 40 kHz and raise its echo.You can calculate the range through the time interval between sending trigger signal and receiving echo signal. the range = high level time * velocity (340M/S) / 2; I suggest to use over 60ms measurement cycle, in order to prevent trigger signal to the echo signal.Then you could calculate the distance, because you have the pulse width by using

    Formula:   Distance_CM= ((Duration of high level)*(Sonic :340m/s))/2.

    That's the gist to start. Please mark correct if this gets you going.

    Clem

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • Verify Answer
    • Cancel
  • Former Member
    0 Former Member over 9 years ago

    Here's some code I adapted for a proximity detector/alarm (I use it to keep my cats off the kitchen counter image ).  One note: This is for a Parallax PING))) sensor, so the trigger and echo (output on the Tx and input on the Rx) are on the same pin.  On the HC-SR04 it uses two separate pins.  I'll put a link to a simple "Instructable" on the the HC-SR04 at the end.

    The main part of my code to look at is the "if" statement with "tone" and "noTone".  The "tone" command takes three parameters: output pin, tone frequency, and duration.  Pretty clean and simple.  As you state, "...[you] are not the best at coding." I'll try to go into some more detail.  I've also tried to put plenty of annotation in the code.

    First, I set constants for the pin the sensor is using and the Arduino on-board LED.  The LED is just for visual feedback.  The serial monitor is used during testing so I can get the sensor distance I want.  You can measure with a ruler, but the sensor is going to have some variation in output based on temp and humidity (it's in the kitchen, after all).  All the lines using a "Serial" function can be deleted or REM'd out, when you have your final setup.

    Then I start the serial monitor and set "ledPin" as an output.

    In the loop section I tell the Arduino to set the variable "cm" to the calculated distance value of the "ping" variable.

    The next part is what will be most relevant to you.  I use an "if" statement to tell a piezo on Arduino digital pin 6 to sound off at a frequency of 2744Hz for 3 seconds (more specifically, 3000 milliseconds), then stop all activity for one second.  The "noTone" command isn't needed with the current library, but I put it in just in case an older "Tone" library was being used (older versions required you to explicitly state you were stopping the tone).  You can use a series of "if" arguments to set various tones at various distances.  You could also use different outputs for the same schema.  "Ideally", you would set a variable and use nested "if" statements, but I thought this might be more confusing.

    The math to calculate distance from the ping time is at the bottom.  The section speaking about the PING))) sensor being triggered by a high of 2 or more microseconds is a debounce function (you can look that up on the Arduino site, or an electronics reference, if it's unfamiliar).

     

    An "Instructable" specific to the HC-SR04 is at: Simple Arduino and HC-SR04 Example .

     

     

    const int pingPin = 5;    /* I could have also used a constant for

                                       the tone pin, but I didn't */

    const int ledPin  = 13; // Arduino pin connected to LED

     

    void setup()

    {

      //Start the serial monitor - Used for testing only

      Serial.begin(9600);

      pinMode(ledPin, OUTPUT);

    }

     

    void loop()

    {

      int cm = ping(pingPin);

     

         if (cm < 15){

         // You would want something like:    if (cm <= 20 && cm >= 15){

         //                                                   tone(x, y, z)

         //                                                  }

         //                                                  if(cm >15 && >= 10){

         //                                                  tone(p, d, q);

         //                                                  }

         //                                                  etc.

        tone(6, 2744, 3000);

        delay(1000);

        // turn off tone function for pin 6:

        noTone(6);

       }

      

    // Inserted print function to add caption

      Serial.print("Inches from target = ");

      Serial.println(cm);   

      digitalWrite(ledPin, HIGH);

      delay(500);

      digitalWrite(ledPin, LOW);

      delay(500);

    }

     

    // returns the distance in cm

    int ping(int pingPin)

    {

      // establish variables for duration of the ping,

      // and the distance result in inches and centimeters:

      long duration, cm;

     

      // The PING))) is triggered by a HIGH pulse of 2 or more microseconds.

      // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:

      pinMode(pingPin, OUTPUT);

      digitalWrite(pingPin, LOW);

      delayMicroseconds(2);

      digitalWrite(pingPin, HIGH);

      delayMicroseconds(5);

      digitalWrite(pingPin, LOW);

     

      pinMode(pingPin, INPUT);

      duration = pulseIn(pingPin, HIGH);

     

      // convert the time into a distance

      cm = microsecondsToCentimeters(duration);

      return cm ;

    }

     

    long microsecondsToCentimeters(long microseconds)

    {

      // The speed of sound is 340 m/s or 29 microseconds per centimeter.

      // The ping travels out and back, so to find the distance of the

      // object we take half of the distance travelled.

      return microseconds / 29 / 2/ 2.54;

      //Added /2.54 to return inches from cm

    }

         

       

    Hopefully this is of some help.

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • Verify Answer
    • Cancel
  • clem57
    0 clem57 over 9 years ago

    Can you mark correct?

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • Verify Answer
    • Cancel
element14 Community

element14 is the first online community specifically for engineers. Connect with your peers and get expert answers to your questions.

  • Members
  • Learn
  • Technologies
  • Challenges & Projects
  • Products
  • Store
  • About Us
  • Feedback & Support
  • FAQs
  • Terms of Use
  • Privacy Policy
  • Legal and Copyright Notices
  • Sitemap
  • Cookies

An Avnet Company © 2025 Premier Farnell Limited. All Rights Reserved.

Premier Farnell Ltd, registered in England and Wales (no 00876412), registered office: Farnell House, Forge Lane, Leeds LS12 2NE.

ICP 备案号 10220084.

Follow element14

  • X
  • Facebook
  • linkedin
  • YouTube