abaout programming emf (Electromagnetic Field)

Excuse me, I would like to inquire about emf detector. I saw one of the projects in makezine.com make emf with arduino, with LED bargraph. but here I replaced it with a small audio (8 Ohm), but why not come up with the perfect voice?

This is my remake program

if(val >= 1){
val = constrain(val, 1, senseLimit);
val = map(val, 1, senseLimit, 1, 1023);

total -= readings[index];
readings[index] = val;
total += readings[index];
index = (index + 1);

if (index >= NUMREADINGS)
index = 0;
average = total / NUMREADINGS;

if (average > 50){
tone(10, 50, 100);
delay(1000);
}

if (average > 150){
tone(10, 50, 200);
delay(1000);
}

if (average > 250){
tone(10,50,300);
delay(1000);
}

if (average > 350){
tone(10,50,400);
delay(1000);
}

if (average > 450){
tone(10,50,500);
delay(1000);
}

if (average > 550){
tone(10,50,600);
delay(1000);
}

if (average > 650){
tone(10,50,700);
delay(1000);
}

if (average > 750){
tone(100,50,800);
delay(1000);
}

Serial.println(average);
delay(updateTime);
}
}

void tone(long duration, int freq) {
duration *= 1000;
int period = (1.0 / freq) * 1000000;
long elapsed_time = 0;
while (elapsed_time < duration) {
digitalWrite(pinSpeaker,HIGH);
delayMicroseconds(period / 2);
digitalWrite(pinSpeaker, LOW);
delayMicroseconds(period / 2);
elapsed_time += (period);

}
}

please answer. Thank’s.

Your calculation of the period is a weird mix of ints and floats. 1/f will be less than 1, which will be zero when converted to an int.

KeithRB:
Your calculation of the period is a weird mix of ints and floats. 1/f will be less than 1, which will be zero when converted to an int.

before I am sorry, I am a beginner. I still do not understand the meaning of your explanation? Can be in clarifying?

(1.0/freq) will be a number between 0 and 1. When converted to an integer, that will be 0. 0 * 1,000,000 is what now? In any case, none of this will fit into an int. Make them unsigned longs, so they can fit numbers this big. So we have:

unsigned long period =(unsigned long) ((1.0/freq) * 1000000.0);

So that the conversion to integer happens after the calculation in floating point.

ETA:
Why not just use the standard tone() command. You would be done by now:

KeithRB:
(1.0/freq) will be a number between 0 and 1. When converted to an integer, that will be 0. 0 * 1,000,000 is what now? In any case, none of this will fit into an int. Make them unsigned longs, so they can fit numbers this big. So we have:

unsigned long period =(unsigned long) ((1.0/freq) * 1000000.0);

So that the conversion to integer happens after the calculation in floating point.

ETA:
Why not just use the standard tone() command. You would be done by now:
http://arduino.cc/en/Reference/Tone

oh, thank you so much. i will try hard. thank you for your attention. :slight_smile: