Advertisement
LightningStalker

Arduino Pot to Frequency

Jan 7th, 2015
1,647
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.28 KB | None | 0 0
  1. //dynamic frequency generator
  2. //50% Duty cycle square wave 1Hz to 1MHz
  3. //for timer2
  4.  
  5. #include <avr/io.h>
  6. #include <avr/interrupt.h>
  7.  
  8. #define TOLERANCE 10
  9.  
  10. unsigned long frequency = 1000000;
  11. int potPin = A0;
  12.  
  13. void setup(){
  14.   pinMode(9,1); // Pins 9 & 10
  15.   pinMode(10,1); // are output.
  16. //Serial.begin(57600);
  17. }
  18.  
  19. int oldVal = 0;
  20.  
  21. void loop(){
  22.   int val = analogRead(potPin);
  23.  
  24.   int diff = abs(val - oldVal); // absolute value
  25.  
  26.   if (diff > TOLERANCE)
  27.   {
  28.     oldVal = val; // only save if the val has changed enough to avoid slowly drifting
  29.     DFG(map(val, 0, 1023, 1, 1000000)); // map 10-bit analog read to freq
  30.   }
  31. }
  32.  
  33. void DFG(unsigned long tempfreq){
  34.   cli();//disable interupts
  35.   TCCR1A = 0;//registers for timer 1
  36.   TCCR1B = 0;
  37.   TCNT1=0;
  38.   TCCR1A |= _BV(COM1A0) + _BV(COM1B0);
  39.   TCCR1B |=_BV(WGM12);
  40.   TCCR1C = _BV(FOC1A);
  41.    if(tempfreq > 122 && tempfreq < 1000001){
  42.   OCR1A = (8000000/tempfreq)-1;//#TIMER COUNTS
  43.   TCCR1B |= _BV(CS10);
  44.   }
  45.   else if(tempfreq <= 122 && tempfreq > 15){
  46.     OCR1A = (1000000/tempfreq)-1;
  47.     TCCR1B |= _BV(CS11);
  48.   }
  49.   else if(tempfreq <= 15 && tempfreq > 4){
  50.     OCR1A = (125000/tempfreq)-1;
  51.     TCCR1B |= _BV(CS10) + _BV(CS11);
  52.   }
  53.  
  54.   //TIMSK1 = _BV(OCIE1A);//TIMER1 COMPARE INTERUPT
  55.   sei();//enable interupts
  56. }
Advertisement
Comments
  • Dancopy
    273 days
    # text 0.24 KB | 0 0
    1. Hi, I can't understand where to connect the pins. In the Arduino code, it is only declared A0 for the Potentiometer and, pinMode(9, 1); // Pins 9 & 10. Is it possible an explanation? If it is easier, my email is: meuviolino@hotmail.com
    2. Thank you
Add Comment
Please, Sign In to add comment
Advertisement