Go Down

Topic: Ping Sensor is Somewhat Working- Random distance reads (Read 408 times) previous topic - next topic

I_Got_Pi

Feb 21, 2013, 07:28 am Last Edit: Feb 21, 2013, 07:53 am by Coding Badly Reason: 1
Hello,

This is not the same question I had earlier about the audio jack. I have finally set up my whole "air piano," and tested it with arduino coding. As a recap, the air piano uses a ping sensor and a 1/8'' audio jack female output. The ping sensor reads the distance between your hand and the sensor, and the arduino determines the sound to output in relation to that distance. My code seems to make sense, and my actual project does to. Here is the setup of my project, and my code.

Setup for Project:
Ping Sensor
-Signal connected to pin 7

1/8'' Audio Female Jack:
-Signal connected to pin 3
-Resistor: 220 ohms

Code:
Code: [Select]
int SensorPin=7;
int AudioPin=3;
int distance;
int note;
unsigned long pulseDuration=0;


void setup() {
 pinMode(AudioPin, OUTPUT);
}

void loop() {
 
 pinMode(SensorPin, OUTPUT); //Sends Ping
 digitalWrite(SensorPin, HIGH);
 delayMicroseconds(5);
 digitalWrite(SensorPin, LOW);
 
 pinMode(SensorPin, INPUT); //Receives ping and calculates centimeter distance
 pulseDuration=pulseIn(SensorPin, HIGH);
 pulseDuration=pulseDuration/2;
 distance = int(pulseDuration/29);
 
 if (distance > 262){
   noTone(AudioPin);  //Makes sure that the sound stays within one C major octave
 }
 
 if (distance < 131){
   noTone(AudioPin);
 }
 
 else{
   distance = note;
   tone(AudioPin, note);
 }
 delay(20); //Take a break
}


My problem is that the speaker ends up outputting random pitches. What am I doing wrong?

Thanks,

I_Got_Pi
   

Moderator edit: [code] [/code] tags added.

PeterH


My problem is that the speaker ends up outputting random pitches. What am I doing wrong?


Do the output glitches correspond to glitches in your position sensing inputs?
I only provide help via the forum - please do not contact me for private consultancy.

AWOL

I'd add some serial debugging prints to find out what your actual values look like.
"Pete, it's a fool looks for logic in the chambers of the human heart." Ulysses Everett McGill.
Do not send technical questions via personal messaging - they will be ignored.

Go Up