I'm using an HC-SR04 ultrasonic rangefinder to control the frequency at which an Arduino pin turns on and off, with the output going via a 1/4" jack plug into my computer's audio interface. (i.e. it's a simple audio oscillator that responds to gestures). This is the code (based on that given here):

#define trigPin 10
#define echoPin 12

void setup() {

  pinMode(trigPin, OUTPUT);
  pinMode(echoPin, INPUT);
  pinMode(9, OUTPUT);


void loop() {

  float duration, distance;
  digitalWrite(trigPin, LOW); // Sends a 2 µs LOW signal to the trigPin     

  digitalWrite(trigPin, HIGH); // Sends a 10 µs HIGH signal to the trigPin
  digitalWrite(trigPin, LOW);

  duration = pulseIn(echoPin, HIGH); //Defines the duration variable

  digitalWrite(9, HIGH); //square wave oscillator 
  digitalWrite(9, LOW);

Pin 9 is the output, and sounds roughly as expected, but what's confusing me is that making any kind of gesture other than very slow ones (i.e. if the distance isn't changing very slowly) causes the output to stop completely for a few seconds, then start again, as if something is overloading and then resetting. What am I doing wrong?

  • @DaveTweed: I reckon this shouldn't have been migrated. The problem is probably in the hardware specification. See my answer. – Transistor Jul 11 '16 at 20:01

I do not really understand the behaviour of your program, but I would like to point out a couple of points that may be problematic:

  1. Your comment says “Sends a 10 µs HIGH signal to the trigPin”, just as the program you based yours on, yet you have a 30 µs delay. If this extra delay makes you miss the rising edge on the echo pin, then pulseIn() will believe it is seen the previous pulse, and it will wait for the next raising edge before starting its measurement. Since that next rising edge will never happen, pulseIn() will eventually time out after one second. This is probably the silence you are hearing.
  2. Your sound frequency may not be what you expect, because the time needed to run through the loop is not only the two calls to delay(), but also the time taken by pulseIn() and the various delayMicroseconds(). You should have more consistent timings if you use the tone() function instead of trying to bit-bang the sound.
| improve this answer | |

Your comments don't match your timing delay values and the datasheet specifies a 10 µs pulse. You're giving it 30 µs but you might get away with it.

I'd look at how often you're triggering the device.

enter image description here

Figure 1. Don't trigger the device more frequently than 40 times per second.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.