There's something happening when UNO is looping fast which I should understand more fully.
My goal is to have a Piezo buzzer buzz at a rate dependent on the light level. Stronger light, higher pitch. Here is my proggie which I adapted from the CIRC-06 Piezo experiment from Ardx.org. Note that there is serial output to see what numbers are being delivered from the map and constrain, also there is a 5 second delay to ensure I can reset and upload without difficulty.
// Colin Beckingham // drive a piezo element according to light level // int pzPin = 9; int ldPin = 0; int lvl = 0; int duration = 0; int i = 0; // void setup() { pinMode(pzPin,OUTPUT); Serial.begin(9600); delay(5000); } // void loop() { // read from light sensor (0-900) lvl = analogRead(ldPin); lvl = map(lvl,0,900,900,8000); lvl = constrain(lvl,900,8000); // output to piezo Serial.println(lvl); playTone(lvl); delay(1000); } // void playTone(int pitch) { for (i=0;i<100;i++) { digitalWrite(pzPin,HIGH); delayMicroseconds(pitch); digitalWrite(pzPin,LOW); delayMicroseconds(pitch); } } The above code works no problem. The issue is when I reduce the 1000 delay in the loop() to zero. (Note: I found that this was in a practical sense a bad idea since my attempts to upload were stifled by the serial output. The Arduino host machine could not "break into" the attached UNO board. So after I succeeded finally I added the delay.) Anyway, while the board was running with no delay the piezo did not vary in pitch. I was expecting that it would rise and fall as light level changed (as it does correctly with the delay in place) but it just put out a steady pitch, the one it started at.
So, something must be happening that I do not yet see. It may be that the difficulty uploading at zero delay and the invariant buzz are the result of the same phenomenon?