Skip to content

Instantly share code, notes, and snippets.

@g1ra
Created October 23, 2022 09:32
Show Gist options
  • Save g1ra/42ffa74790ebe0afaa802d98d4802faf to your computer and use it in GitHub Desktop.
Save g1ra/42ffa74790ebe0afaa802d98d4802faf to your computer and use it in GitHub Desktop.
#include<avr/io.h>
const int Output = 4; // Can be 1 or 4
const int LED = 1;
// Cater for 16MHz, 8MHz, or 1MHz clock:
const int Clock = ((F_CPU/1000000UL) == 16) ? 4 : ((F_CPU/1000000UL) == 8) ? 3 : 0;
const uint8_t scale[] PROGMEM = {239,226,213,201,190,179,169,160,151,142,134,127};
void note (int n, int octave) {
int prescaler = 8 + Clock - (octave + n/12);
if (prescaler<1 || prescaler>15 || octave==0) prescaler = 0;
DDRB = (DDRB & ~(1<<Output)) | (prescaler != 0)<<Output;
OCR1C = pgm_read_byte(&scale[n % 12]) - 1;
GTCCR = (Output == 4)<<COM1B0;
TCCR1 = 1<<CTC1 | (Output == 1)<<COM1A0 | prescaler<<CS10;
}
void Beep() {
TCCR1 = TCCR1 | 3; // Counter = clock/4
}
void NoBeep() {
TCCR1 = TCCR1 & ~3; // Counter stopped
}
void setup() {
pinMode(Output, OUTPUT);
// pinMode(LED, OUTPUT);
// Setup beep
TCCR1 = 1<<CTC1 | 0<<COM1A0 | 0<<CS10; // CTC mode, counter stopped
GTCCR = 1<<COM1B0; // Toggle OC1B (PB4)
OCR1C = 189; // Plays 1042Hz (C6)
// digitalWrite(LED, HIGH);
}
void loop() {
for (int n=0; n<=12; n++) {
// note(0, 4);
Beep();
// note(0, 4);
delay(500);
NoBeep();
// note(0, 0);
delay(500);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment