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
delayMicroseconds(30);
digitalWrite(trigPin, HIGH); // Sends a 10 μs HIGH signal to the trigPin
delayMicroseconds(30);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH); //Defines the duration variable
digitalWrite(9, HIGH); //square wave oscillator
delay(0.1+duration*0.01);
digitalWrite(9, LOW);
delay(0.1+duration*0.01);
}
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– Transistor2016年07月11日 20:01:07 +00:00Commented Jul 11, 2016 at 20:01
2 Answers 2
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:
- 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. - 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 bypulseIn()
and the variousdelayMicroseconds()
. You should have more consistent timings if you use thetone()
function instead of trying to bit-bang the sound.
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.
Figure 1. Don't trigger the device more frequently than 40 times per second.