Final code.

Could add some comments
This commit is contained in:
David Lenfesty 2019-10-20 18:07:01 -06:00 committed by GitHub
parent 2d4a3fba3e
commit 008c33b99f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 34 additions and 38 deletions

View File

@ -7,22 +7,13 @@
#include "main.h"
uint8_t play_flag = 0;
uint8_t button_flag = 0;
ISR(INT0_vect) {
// Disable interrupts
cli();
// Notify of button press
button_flag = 1;
}
bool play_flag = 0;
/*
* Pin Definitions:
* PB2 -> OC0A output
* PB3 -> OC1A output
* PB0 -> Switch Input
* PD2 -> Switch Input
*/
void gpio_init() {
// Piezo Out
@ -31,13 +22,6 @@ void gpio_init() {
// Switch Input Setup
DDRD &= ~(1 << DDD2);
PORTD |= (1 << PORTD2);
// Configure Interrupt Stuff
// Set falling edge for INT0
MCUCR |= (1 << ISC01) | (0 << ISC00);
// Enable INT0
GIMSK |= (1 << INT0);
}
void timer_init( ) {
@ -53,7 +37,9 @@ void timer_init( ) {
TCCR1B = (1 << WGM12);
}
void play_beat() {
// Returns true for a "successful" note, false for end of song.
bool play_beat() {
static uint8_t duration_left[2] = {0};
static uint16_t song_location[2] = {0};
@ -61,6 +47,7 @@ void play_beat() {
if (song_location[0] == SPEAKER0_LEN) {
song_location[0] = 0;
song_location[1] = 0;
return false;
}
// Set note
@ -112,40 +99,38 @@ void play_beat() {
}
_delay_ms(BEAT_LENGTH * REST_FRACTION);
return true;
}
int main(void)
{
gpio_init();
timer_init();
sei();
/* Replace with your application code */
beat_t beat = {
.note = a,
.duration = 20,
.octave = 0,
};
play_note(beat, 1);
while (1)
{
if (play_flag) {
play_beat();
}
if (button_flag) {
button_flag = 0;
if (bit_is_clear(PIND, PIND2)) {
// Play song until the end
while(play_beat());
// Turn off speakers once song is over
beat_t beat = {
.note = rest,
.duration = 0,
.octave = 0, // octave doesn't matter, its a rest
};
play_note(beat, 0);
play_note(beat, 1);
_delay_ms(100);
sei();
}
if ( bit_is_clear(PIND, PIND2) && (play_flag == 0)) {
cli();
play_flag = 1;
_delay_ms(100);
sei();
}
}
}

View File

@ -8,17 +8,24 @@
#include <avr/pgmspace.h>
#include <util/delay.h>
#include "notes.h"
#include <stdbool.h>
#define TEMPO (120 * 4) // Tempo of song (bpm)
#define REST_FRACTION 0.3 // Fraction of the beat to stay silent between notes
#define BEAT_LENGTH 60000 / TEMPO // Length of each note (ms)
// Song Selection
#define CRAB_RAVE
#define OCTAVES 2
#define NOTES_PER_OCTAVE 12
#ifdef CRAB_RAVE
#define SPEAKER0_LEN 38
#define SPEAKER1_LEN 96
#endif
typedef enum {
a = 0, b, c, d, e, f, g,

View File

@ -1,5 +1,7 @@
#include "main.h"
#ifdef CRAB_RAVE
const beat_t PROGMEM song_speaker0[SPEAKER0_LEN] = {
{.note = g, .duration = 4, .octave = 0 },
{.note = g, .duration = 4, .octave = 0 },
@ -139,3 +141,5 @@ const beat_t PROGMEM song_speaker1[SPEAKER1_LEN] = {
{.note = f, .duration = 1, .octave = 1 },
{.note = e, .duration = 1, .octave = 1},
};
#endif