Last active
December 3, 2021 10:44
-
-
Save paulhayes/7a3929a6ac06f20bc082bf2de6815839 to your computer and use it in GitHub Desktop.
For Atmel ATTiny13A microcontroller. Output generated on PB0 ( D0 )
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#define SPEAKER_PIN PB0 | |
static void timer_set(uint8_t OCRxn, uint8_t N); | |
static void timer_clear(); | |
static void tone(uint16_t freq); | |
static void notone(); | |
void enable_tone() | |
{ | |
TCCR0A |= _BV(WGM01); // set timer mode to Fast PWM | |
TCCR0A |= _BV(COM0A0); // connect PWM pin to Channel A of Timer0 | |
} | |
void disable_tone() | |
{ | |
TCCR0A &= ~_BV(WGM01); // set timer mode to Fast PWM | |
TCCR0A &= ~_BV(COM0A0); // connect PWM pin to Channel A of Timer0 | |
} | |
void notone(){ | |
TCCR0A &= ~_BV(WGM01); | |
TCCR0A &= ~_BV(COM0A0); | |
} | |
void tone(uint16_t freq){ | |
if(freq==0){ | |
notone(); | |
return; | |
} | |
TCCR0A |= _BV(WGM01); // set timer mode to Fast PWM, Clear Timer on Compare Match | |
TCCR0A |= _BV(COM0A0); // connect PWM pin to Channel A of Timer0, Toggle OC0A on Compare Match | |
uint16_t prescalerIndex = 0; | |
uint16_t prescalers[] = { | |
0,1,8,64,256,1024 | |
}; | |
uint32_t modulo; | |
do { | |
prescalerIndex++; | |
modulo = F_CPU/(freq*2L*prescalers[prescalerIndex]); | |
} while(modulo>=256); | |
timer_set(modulo,prescalerIndex); | |
} | |
void timer_clear() | |
{ | |
timer_set(1, 0); | |
} | |
void timer_set(uint8_t OCRxn, uint8_t prescaler) | |
{ | |
TCCR0B = (TCCR0B & ~(_BV(CS02)|_BV(CS01)|_BV(CS00))) | prescaler; | |
OCR0A = OCRxn - 1; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment