123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175 |
- #include "system_timer.h"
- #ifdef SYSTEM_TIMER_2
- #include <avr/io.h>
- #include <avr/interrupt.h>
- #include "Arduino.h"
- #include "io_atmega2560.h"
- #define BEEPER 84
- uint8_t timer02_pwm0 = 0;
- void timer02_set_pwm0(uint8_t pwm0)
- {
- if (timer02_pwm0 == pwm0) return;
- if (pwm0)
- {
- TCCR0A |= (2 << COM0B0);
- OCR0B = pwm0 - 1;
- }
- else
- {
- TCCR0A &= ~(2 << COM0B0);
- OCR0B = 0;
- }
- timer02_pwm0 = pwm0;
- }
- void timer02_init(void)
- {
-
- uint8_t _sreg = SREG;
-
- cli();
-
- TIMSK0 &= ~(1<<TOIE0);
- TIMSK0 &= ~(1<<OCIE0A);
- TIMSK0 &= ~(1<<OCIE0B);
-
- TCCR0A = 0x00;
- TCCR0B = (1 << CS00);
-
- TCCR0A |= (3 << WGM00);
-
- OCR0B = 0;
-
- TCCR0A &= ~(2 << COM0B0);
-
- TCCR2A = 0x00;
- TCCR2B = (4 << CS20);
-
- TIMSK2 |= (1<<TOIE2);
- TIMSK2 &= ~(1<<OCIE2A);
- TIMSK2 &= ~(1<<OCIE2B);
-
- OCR2A = 0;
- OCR2B = 128;
-
- SREG = _sreg;
- }
- #define MICROSECONDS_PER_TIMER0_OVERFLOW (clockCyclesToMicroseconds(64 * 256))
- #define MILLIS_INC (MICROSECONDS_PER_TIMER0_OVERFLOW / 1000)
- #define FRACT_INC ((MICROSECONDS_PER_TIMER0_OVERFLOW % 1000) >> 3)
- #define FRACT_MAX (1000 >> 3)
- volatile unsigned long timer2_overflow_count;
- volatile unsigned long timer2_millis;
- unsigned char timer2_fract = 0;
- ISR(TIMER2_OVF_vect)
- {
-
-
- unsigned long m = timer2_millis;
- unsigned char f = timer2_fract;
- m += MILLIS_INC;
- f += FRACT_INC;
- if (f >= FRACT_MAX)
- {
- f -= FRACT_MAX;
- m += 1;
- }
- timer2_fract = f;
- timer2_millis = m;
- timer2_overflow_count++;
- }
- unsigned long millis2(void)
- {
- unsigned long m;
- uint8_t oldSREG = SREG;
-
-
- cli();
- m = timer2_millis;
- SREG = oldSREG;
- return m;
- }
- unsigned long micros2(void)
- {
- unsigned long m;
- uint8_t oldSREG = SREG, t;
- cli();
- m = timer2_overflow_count;
- #if defined(TCNT2)
- t = TCNT2;
- #elif defined(TCNT2L)
- t = TCNT2L;
- #else
- #error TIMER 2 not defined
- #endif
- #ifdef TIFR2
- if ((TIFR2 & _BV(TOV2)) && (t < 255))
- m++;
- #else
- if ((TIFR & _BV(TOV2)) && (t < 255))
- m++;
- #endif
- SREG = oldSREG;
- return ((m << 8) + t) * (64 / clockCyclesPerMicrosecond());
- }
- void delay2(unsigned long ms)
- {
- uint32_t start = micros2();
- while (ms > 0)
- {
- yield();
- while ( ms > 0 && (micros2() - start) >= 1000)
- {
- ms--;
- start += 1000;
- }
- }
- }
- void tone2(__attribute__((unused)) uint8_t _pin, __attribute__((unused)) unsigned int frequency)
- {
- PIN_SET(BEEPER);
- }
- void noTone2(__attribute__((unused)) uint8_t _pin)
- {
- PIN_CLR(BEEPER);
- }
- #endif
|