int ledPin = 13; // LED connected to digital pin 13
long randOn = 0; // Initialize a variable for the ON time
long randOff = 0; // Initialize a variable for the OFF time
void setup() // run once, when the sketch starts
{
randomSeed (analogRead (0)); // randomize
pinMode(ledPin, OUTPUT); // sets the digital pin as output
}
void loop() // run over and over again
{
randOn = random (100, 1200); // generate ON time between 0.1 and 1.2 seconds
randOff = random (200, 900); // generate OFF time between 0.2 and 0.9 seconds
digitalWrite(ledPin, HIGH); // sets the LED on
delay(randOn); // waits for a random time while ON
digitalWrite(ledPin, LOW); // sets the LED off
delay(randOff); // waits for a random time while OFF
}
i thought that if i conected a speaker right to the pin output i would get a tone, but aparently not. I only get a very low click...
the idea is to repeat the same tone at random times.
Not sure why I persist in trying to get this across, I guess the I thought the technique was worth sharing.
So if . . .
you want to actually drive a speaker & can connect it properly
you don't want to use the tone lib
than this change to your code should give you the loudest sound since it's like using 10V peak to peak . . .
int speakPinA = 13; // ONE SIDE OF SPEAKER (using int is silly BTW)
int speakPinB = 12; // OTHER SIDE OF SPEAKER
long randOn = 0; // Initialize a variable for the ON time
long randOff = 0; // Initialize a variable for the OFF time
void setup() // run once, when the sketch starts
{
randomSeed (analogRead (0)); // randomize
pinMode(speakPinA, OUTPUT); // sets the digital pin as output
pinMode(speakPinB, OUTPUT); // sets the digital pin as output
}
void loop() // run over and over again
{
randOn = random (100, 1200); // generate ON time between 0.1 and 1.2 seconds
randOff = random (200, 900); // generate OFF time between 0.2 and 0.9 seconds
digitalWrite(speakPinA, HIGH); // pushes speaker/piezo cone out
digitalWrite(speakPinB, LOW);
delay(randOn); // waits for a random time while ON
digitalWrite(speakPinA, LOW); // pulls speaker/piezo cone in
digitalWrite(speakPinB, HIGH);
delay(randOff); // waits for a random time while OFF
}
Otherwise take the trouble to understand the tone lib.
BTW if you are making something like a simulated Geiger counter sound and just want random "clicks" you may be better off with a piezo.
Find one of the resonant freqs. of the piezo, and create short bursts (~5mS). It will sound like a click.
[edit]Tried this at home and noticed I forget to add pinMode(speakPinB, OUTPUT);. Corrected the example above. Technique makes a significant difference in the volume of a piezo. [/edit]