In this snippet of code we introduced thewhile ( 1 ) {
digitalWrite(speakerPin, HIGH);
delayMicroseconds(500);
digitalWrite(speakerPin, LOW);
delayMicroseconds(500);
}
while()
loop. The while loop is very similar to how the void loop()
works in every arduino program as in it will loop over the code in it's block over and over again. However, unlike the void loop()
, the while loop needs a condition to be true in order to keep looping. This is similar to an if
statement. while(1)
. This results in an infinite loop because '1' is always treated as true and since the 1 will never change, the contents of the while loop will repeat itself over and over again. This means it will never leave the loop, meaning it won't execute any other code besides its contents. Arduino Mega | Arduino Uno |
Click the image for full size! |
int speakerPin = 9; |
int controlPin = 0; |
|
void setup() { |
pinMode(speakerPin, OUTPUT); |
} |
|
/* |
|
play a tone with period given in microseconds for a duration |
given in milliseconds |
|
*/ |
void playTone(int period, int duration) { |
// elapsed time in microseconds, the long is needed to get |
// a big enough range. |
|
long elapsedTime = 0; |
|
// note we are making a slight error here if period is not even |
int halfPeriod = period / 2; |
|
while (elapsedTime < duration * 1000L) { |
// generate a square wave of the given period. Half the |
// period is on, the other half is off. |
digitalWrite(speakerPin, HIGH); |
delayMicroseconds(halfPeriod); |
|
digitalWrite(speakerPin, LOW); |
delayMicroseconds(halfPeriod); |
|
// count the time we just consumed for one cycle of the tone |
elapsedTime = elapsedTime + period; |
} |
|
} |
|
void loop() { |
int period; |
|
period = analogRead(controlPin); |
playTone(period, 500); |
} |
map
function to convert this into a period that ranges from 100 uS to 10000 uS. In summary, the map function is used like this: mappedVal = map(oldVal, oldLow, oldHigh, newLow, newHigh)
5. Lab 3 - Making and Controlling Sound Arduino Intro Labs for Tangible Computing / Version 1.00 2012-09-24 |