PingPong/Core/Inc/Sound.h
2024-10-03 02:37:05 +03:00

173 lines
3.4 KiB
C

/*
* Sound.h
*
* Created on: Oct 1, 2024
* Author: DashyFox
*/
#ifndef INC_SOUND_H_
#define INC_SOUND_H_
#include <stdint.h>
// Define default timer and channels
#define SOUND_TIMER TIM4
#define SOUND_TIMER_RCC RCC_APB1ENR_TIM4EN
extern uint32_t bpm;
// Define the Note structure
typedef struct {
uint32_t frequency; // Frequency in Hz
uint32_t duration; // Duration in milliseconds, 0 means infinite
uint8_t duty_cycle; // PWM duty cycle in percentage (0-100)
} Note_t;
// Enum for musical notes
typedef enum {
C0 = 16,
C0_sharp = 17,
D0 = 18,
D0_sharp = 19,
E0 = 21,
F0 = 22,
F0_sharp = 23,
G0 = 25,
G0_sharp = 26,
A0 = 28,
A0_sharp = 29,
B0 = 31,
C1 = 33,
C1_sharp = 35,
D1 = 37,
D1_sharp = 39,
E1 = 41,
F1 = 44,
F1_sharp = 46,
G1 = 49,
G1_sharp = 52,
A1 = 55,
A1_sharp = 58,
B1 = 62,
C2 = 65,
C2_sharp = 69,
D2 = 73,
D2_sharp = 78,
E2 = 82,
F2 = 87,
F2_sharp = 92,
G2 = 98,
G2_sharp = 104,
A2 = 110,
A2_sharp = 117,
B2 = 123,
C3 = 130,
C3_sharp = 138,
D3 = 146,
D3_sharp = 155,
E3 = 164,
F3 = 174,
F3_sharp = 185,
G3 = 196,
G3_sharp = 207,
A3 = 220,
A3_sharp = 233,
B3 = 246,
C4 = 261,
C4_sharp = 277,
D4 = 293,
D4_sharp = 311,
E4 = 329,
F4 = 349,
F4_sharp = 369,
G4 = 392,
G4_sharp = 415,
A4 = 440,
A4_sharp = 466,
B4 = 493,
C5 = 523,
C5_sharp = 554,
D5 = 587,
D5_sharp = 622,
E5 = 659,
F5 = 698,
F5_sharp = 740,
G5 = 784,
G5_sharp = 830,
A5 = 880,
A5_sharp = 932,
B5 = 987,
C6 = 1046,
C6_sharp = 1108,
D6 = 1174,
D6_sharp = 1244,
E6 = 1318,
F6 = 1396,
F6_sharp = 1480,
G6 = 1568,
G6_sharp = 1661,
A6 = 1760,
A6_sharp = 1864,
B6 = 1975,
C7 = 2093,
C7_sharp = 2217,
D7 = 2349,
D7_sharp = 2489,
E7 = 2637,
F7 = 2793,
F7_sharp = 2960,
G7 = 3136,
G7_sharp = 3322,
A7 = 3520,
A7_sharp = 3729,
B7 = 3951,
C8 = 4186,
C8_sharp = 4435,
D8 = 4699,
D8_sharp = 4978
} MusicalNote_t;
// Enum for note durations (in fractions of a whole note)
typedef enum {
T0 = 0, // Infinite
T1 = 1, // Whole note
T2 = 2, // Half note
T4 = 4, // Quarter note
T8 = 8, // Eighth note
T16 = 16 // Sixteenth note
} NoteDuration_t;
// Structure for melody playback
typedef struct {
Note_t* notes; // Pointer to an array of notes
uint32_t size; // Number of notes in the melody
uint32_t current_note; // Index of the current note
uint32_t repeat_count; // Total repeat count
uint32_t repeat_left; // Repeats left
} Melody_t;
// Function declarations
void sound_init(void);
void sound_set_bpm(uint32_t bpm);
void sound_play_note(Note_t note, uint8_t channel);
void sound_play_melody(Note_t* melody, uint32_t size, uint8_t channel, uint32_t repeat_count);
void sound_play_melody(Note_t* melody, uint32_t size, uint8_t channel, uint32_t repeat_count);
void sound_tick(void);
uint16_t get_array_size(Note_t *array);
Note_t sound_create_note(MusicalNote_t note, NoteDuration_t duration, uint8_t duty_cycle);
#define CREATE_NOTE(note, dur, duty) \
((Note_t){ .frequency = note, .duration = dur, .duty_cycle = duty })
#endif /* INC_SOUND_H_ */