Examples - Electronic Bricks - Electronic Brick Sound

How to generate sound with the Electronik Brick Piezzo Speaker.

That program gives you a basic understanding how to deal with sound using the Rotary and Speaker Electronic Brick.



/*
Interactiv tones - Squarewave
Example: Analog input and analog output
Use the rotary to change tone height

Math formula: timeHigh = period / 2 = 1 / (2 * toneFrequency)

* note 	frequency 	period 	timeHigh(tone)
* c 	        261 Hz 	        3830 	1915
* d 	        294 Hz 	        3400 	1700
* e 	        329 Hz 	        3038 	1519
* f 	        349 Hz 	        2864 	1432
* g 	        392 Hz 	        2550 	1275
* a 	        440 Hz 	        2272 	1136
* b 	        493 Hz 	        2028	1014
* C	        523 Hz	        1912 	956

*/

int val;                      // Input value from rotary
int rotaryPin = 1;            // Analog input rotary
int speakerPin = 9;           // Analog output to speaker
int toneDuration = 1000;      // Tone duration in ms


/*
Function  makeTone
Generates a squarewave tone with an duration
*/
void makeTone(int tone, int duration)
{
        for (long i = 0; i < duration * 1000L; i += tone * 2)
        {
                digitalWrite(speakerPin, HIGH);
                delayMicroseconds(tone);
                digitalWrite(speakerPin, LOW);
                delayMicroseconds(tone);
        }
}


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

void loop() {
        val = analogRead(rotaryPin);     // Read the rotary analog value
        makeTone(val, toneDuration);     // Play sound
}

This website has been archived and is no longer maintained.