Skip to content

Instantly share code, notes, and snippets.

@paulhayes
Last active December 3, 2021 10:44
Show Gist options
  • Save paulhayes/7a3929a6ac06f20bc082bf2de6815839 to your computer and use it in GitHub Desktop.
Save paulhayes/7a3929a6ac06f20bc082bf2de6815839 to your computer and use it in GitHub Desktop.
For Atmel ATTiny13A microcontroller. Output generated on PB0 ( D0 )
#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