Advertisement
Szerelo

Ultra low frequency generator with tone() function

Aug 22nd, 2019
270
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.71 KB | None | 0 0
  1. /*
  2.  * Ultra low frequency generator with tone() function
  3.  * Created by Szerelo
  4.  * If you use it, mention the author. Thanks :)
  5.  */
  6.    
  7. int interruptCounter=0;
  8. int freq=1000;        // Starting frequency
  9. int dividerValue=100;  // Divider of Tone(). If it is even lower, increase its value.
  10. byte count=0;
  11.  
  12. #define BUP 12    // Button frequency+
  13. #define BDOWN 11  // Button frequency-
  14. #define OutFreqH 3   // Hardware interrupt pin only
  15. #define OutFreqL 2
  16.  
  17. void setup() {
  18.   Serial.begin(115200);
  19.   Serial.println("Start generator");
  20.   pinMode(BUP,INPUT_PULLUP);
  21.   pinMode(BDOWN,INPUT_PULLUP);
  22.   pinMode(OutFreqH,OUTPUT);
  23.   pinMode(OutFreqL,OUTPUT);
  24.   attachInterrupt(digitalPinToInterrupt(OutFreqH), inInterrupt, CHANGE);
  25.   tone(OutFreqH,freq);  
  26. }
  27.  
  28. void inInterrupt () {
  29.   interruptCounter++;
  30.   if (interruptCounter==dividerValue) {  // The tone() frequency divide with dividerValue.
  31.     interruptCounter=0;
  32.     digitalWrite(OutFreqL,!digitalRead(OutFreqL));  // Output toggle.
  33.   }
  34. }
  35.  
  36. void loop() {
  37.   if (digitalRead(BUP)==HIGH and digitalRead(BDOWN)==HIGH) count=0;   // Button pressing time counter clear.
  38.   if (digitalRead(BUP)==LOW and freq<20000) {  // Maximum value 20000
  39.     freq++;
  40.     count++;    // Button pressing time increased.
  41.     if (count==50) {  // If the button pressing lond time, the freq increment 10.
  42.       count=49;
  43.       freq=freq+9;
  44.     }
  45.     tone(OutFreqH,freq);  
  46.     Serial.println(freq);
  47.     delay(100);
  48.   }
  49.   if (digitalRead(BDOWN)==LOW and freq>31) {  // The Tone() function minimum value is 31.
  50.     freq--;
  51.     count++;
  52.     if (count==50) {
  53.       count=49;
  54.       freq=freq-9;
  55.     }
  56.     tone(OutFreqH,freq);  
  57.     Serial.println(freq);
  58.     delay(100);
  59.   }
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement