Arduino - vlastné tóny cez timer2

From DT^2
Revision as of 07:27, 10 August 2018 by Admin (talk | contribs) (Created page with "<syntaxhighlight lang="C" line="line"> #define SIRENE_PORT PORTB #define SIRENE_DDR DDRB #define SIRENE_PIN 4 void setup() { init_tone2(); } volatile uint32_t ever =...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search
  1 #define SIRENE_PORT  PORTB
  2 #define SIRENE_DDR   DDRB
  3 #define SIRENE_PIN   4
  4 
  5 void setup() {
  6   init_tone2();
  7 }
  8 
  9 volatile uint32_t ever = 0;
 10 
 11 void loop() {
 12 
 13   delay(2000);
 14   for (int i = 0; i < 2; i++)
 15   {
 16     tone2(262, 200);
 17     delay(200);
 18     tone2(330, 200);
 19     delay(200);
 20   
 21     tone2(262, 200);
 22     delay(200);
 23     tone2(330, 200);
 24     delay(200);
 25   
 26     tone2(392, 400);
 27     delay(400);
 28   
 29     tone2(392, 400);
 30     delay(400);
 31   }
 32 }
 33 
 34 void init_tone2()
 35 {
 36   TCCR2A = 2;
 37   TCCR2B = 0;
 38   TIMSK2 = 2;
 39   SIRENE_DDR |= (1 << SIRENE_PIN);  
 40 }
 41 
 42 static volatile uint8_t tone2_state;
 43 static volatile uint32_t tone2_len;
 44 
 45 ISR(TIMER2_COMPA_vect)
 46 {
 47   ever++;
 48   if (tone2_state) 
 49   {
 50     SIRENE_PORT |= (1 << SIRENE_PIN);
 51     tone2_state = 0;
 52   }
 53   else 
 54   {
 55     SIRENE_PORT &= ~(1 << SIRENE_PIN);
 56     tone2_state = 1;
 57   }
 58   if ((--tone2_len) == 0) TCCR2B = 0;
 59 }
 60 
 61 void tone2(uint16_t freq, uint16_t duration)
 62 {
 63   uint32_t period = 1000000 / freq;
 64 
 65   if (freq >= 977)  // prescaler 32
 66   {
 67     tone2_state = 0;
 68     tone2_len = ((uint32_t)duration * (uint32_t)1000) * 2 / period;
 69     TCNT2 = 0;
 70     OCR2A = (uint8_t) (250000 / (uint32_t)freq);
 71     TCCR2B = 3;
 72   }
 73   else if (freq >= 488) // prescaler 64
 74   {
 75     tone2_state = 0;
 76     tone2_len = ((uint32_t)duration * (uint32_t)1000) * 2 / period;
 77     TCNT2 = 0;
 78     OCR2A = (uint8_t) (125000 / (uint32_t)freq);
 79     TCCR2B = 4;    
 80   }
 81   else if (freq >= 244) // prescaler 128
 82   {
 83     tone2_state = 0;
 84     tone2_len = ((uint32_t)duration * (uint32_t)1000) * 2 / period;
 85     TCNT2 = 0;
 86     OCR2A = (uint8_t) (62500 / (uint32_t)freq);
 87     TCCR2B = 5;
 88   }
 89   else if (freq >= 122) //prescaler 256
 90   {
 91     tone2_state = 0;
 92     tone2_len = ((uint32_t)duration * (uint32_t)1000) * 2 / period;
 93     TCNT2 = 0;
 94     OCR2A = (uint8_t) (31250 / (uint32_t)freq);
 95     TCCR2B = 6;
 96   }
 97   else if (freq >= 30) //prescaler 1024
 98   {
 99     tone2_state = 0;
100     tone2_len = ((uint32_t)duration * (uint32_t)1000) * 2 / period;
101     TCNT2 = 0;
102     OCR2A = (uint8_t) (7813 / (uint32_t)freq);
103     TCCR2B = 7;
104   }
105 }