Advertisement
Guest User

Untitled

a guest
Nov 24th, 2017
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.32 KB | None | 0 0
  1. /*
  2. * Generate the fastest oscillation frequency possible from digital output
  3. */
  4.  
  5. //
  6. // Use of timer2 to generate a signal for a particular frequency on pin 11
  7. //
  8. //
  9.  
  10. const int freqOutputPin = 11; // OC2A output pin for ATmega328 boards
  11. //const int freqOutputPin = 10; // OC2A output for Mega boards
  12.  
  13. // Constants are computed at compile time
  14.  
  15. // If you change the prescale value, it affects CS22, CS21, and CS20
  16. // For a given prescale value, the eight-bit number that you
  17. // load into OCR2A determines the frequency according to the
  18. // following formulas:
  19. //
  20. // With no prescaling, an ocr2val of 3 causes the output pin to
  21. // toggle the value every four CPU clock cycles. That is, the
  22. // period is equal to eight slock cycles.
  23. //
  24. // With F_CPU = 16 MHz, the result is 2 MHz.
  25. //
  26. // Note that the prescale value is just for printing; changing it here
  27. // does not change the clock division ratio for the timer! To change
  28. // the timer prescale division, use different bits for CS22:0 below
  29. const int prescale = 1;
  30. const int ocr2aval = 3;
  31. // The following are scaled for convenient printing
  32. //
  33.  
  34. // Period in microseconds
  35. const float period = 2.0 * prescale * (ocr2aval+1) / (F_CPU/1.0e6);
  36.  
  37. // Frequency in Hz
  38. const float freq = 1.0e6 / period;
  39.  
  40. void setup()
  41. {
  42. pinMode(freqOutputPin, OUTPUT);
  43. Serial.begin(9600);
  44.  
  45. // Set Timer 2 CTC mode with no prescaling. OC2A toggles on compare match
  46. //
  47. // WGM22:0 = 010: CTC Mode, toggle OC
  48. // WGM2 bits 1 and 0 are in TCCR2A,
  49. // WGM2 bit 2 is in TCCR2B
  50. // COM2A0 sets OC2A (arduino pin 11 on Uno or Duemilanove) to toggle on compare match
  51. //
  52. TCCR2A = ((1 << WGM21) | (1 << COM2A0));
  53.  
  54. // Set Timer 2 No prescaling (i.e. prescale division = 1)
  55. //
  56. // CS22:0 = 001: Use CPU clock with no prescaling
  57. // CS2 bits 2:0 are all in TCCR2B
  58. TCCR2B = (1 << CS20);
  59.  
  60. // Make sure Compare-match register A interrupt for timer2 is disabled
  61. TIMSK2 = 0;
  62. // This value determines the output frequency
  63. OCR2A = ocr2aval;
  64.  
  65. Serial.print("Period = ");
  66. Serial.print(period);
  67. Serial.println(" microseconds");
  68. Serial.print("Frequency = ");
  69. Serial.print(freq);
  70. Serial.println(" Hz");
  71. }
  72.  
  73.  
  74. void loop()
  75. {
  76. cli();
  77. OCR1A = 1;
  78. sei();
  79. delay(1);
  80. cli();
  81. OCR1A = 3;
  82. sei();
  83. delay(1);
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement