You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

62 lines
1.9 KiB
C++

/*
*
* Simple (PWM) Oscillator Explained
*
Instead of using the Tone() function, you can create a square wave oscillator by
turning the digital pin 11 (speakerpin) on (HIGH) and off (LOW) very fast:
|
HIGH | ___ ___
| | | | | 50% duty cycle
LOW | ____| |____| | (50% on, 50 off) Determined by delayMicroseconds()
|
|____________________
TIME
*
*
*
*
*
*/
#define SPEAKER_PIN 11
void setup() {
// set pin 11 as output
pinMode(SPEAKER_PIN, OUTPUT);
}
void loop() {
//in simple-osc.ino we use tone(outputpin, 1000); to make a 1000Hz tone
//1000Hz means 1000x on and off in one second.
//instead of using tone(), we can write out what happens:
//turn on a pin on and of on/off 1000x per second:
digitalWrite( SPEAKER_PIN, LOW ); //turn pin off
delayMicroseconds( 500 ); // wait
digitalWrite( SPEAKER_PIN, HIGH );//tunr pin on
delayMicroseconds( 500 ); // wait
//the wait period determains how long it takes to loop through the
//code, and thus how fast the code runs, and thus how fast
//the pin turns on and off and thus at what frequency this happens:
//we get an oscillation (on-off)!
//Maths:
// for 1Hz, the pin goes on and off in one second. So the delay should be 0.5 second
// for 1000Hz the pin goes on/off 1000x in 1 sec. So the delay should be 1000x smaller: 0.0005 seconds
// wich is 500 micro seconds (dont confuse milliseconds with microseconds).
//To control the frequency with a knob we can use analogRead, uncomment the code below (and comment out the one above):
// digitalWrite( SPEAKER_PIN, LOW ); //turn pin off
// delayMicroseconds( analogRead(A2) ); // wait
// digitalWrite( SPEAKER_PIN, HIGH );//tunr pin on
// delayMicroseconds( analogRead(A2) ); // wait
}