ECE3849/audio.c
2025-04-24 12:52:49 -04:00

65 lines
2.2 KiB
C

#include <stdint.h>
#include <stdbool.h>
#include "driverlib/pwm.h"
#include "driverlib/sysctl.h"
#include "driverlib/gpio.h"
#include "driverlib/timer.h"
#include "driverlib/pin_map.h"
#include "inc/tm4c1294ncpdt.h"
#include "driverlib/interrupt.h"
#include "inc/hw_types.h"
#include "inc/hw_memmap.h"
#include "driverlib/fpu.h"
#include <math.h>
#include "driverlib/pwm.h"
#include <stdlib.h>
#include "audio_waveform.h"
#include "frequency.h"
#define AUDIO_PWM_PERIOD 258
uint32_t gSamplingRateDivider = 29; // sampling rate divider
void configure_audio() {
// configure M0PWM2, at GPIO PF2, BoosterPack 1 header C1 pin 2
SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOG);
GPIOPinTypePWM(GPIO_PORTG_BASE, GPIO_PIN_1);
GPIOPinConfigure(GPIO_PG1_M0PWM5);
GPIOPadConfigSet(GPIO_PORTG_BASE, GPIO_PIN_1, GPIO_STRENGTH_2MA,
GPIO_PIN_TYPE_STD);
// configure the PWM0 peripheral, gen 2, outputs 5
SysCtlPeripheralEnable(SYSCTL_PERIPH_PWM0);
// use system clock without division
PWMClockSet(PWM0_BASE, PWM_SYSCLK_DIV_1);
PWMGenConfigure(PWM0_BASE, PWM_GEN_2,
PWM_GEN_MODE_DOWN | PWM_GEN_MODE_NO_SYNC);
PWMGenPeriodSet(PWM0_BASE, PWM_GEN_2,
AUDIO_PWM_PERIOD);
PWMPulseWidthSet(PWM0_BASE, PWM_OUT_5,
roundf((float)AUDIO_PWM_PERIOD * 0.5f));
gSamplingRateDivider = gSystemClock / AUDIO_PWM_PERIOD / AUDIO_SAMPLING_RATE;
PWMGenIntTrigEnable(PWM0_BASE, PWM_GEN_2, PWM_INT_CNT_ZERO);
PWMOutputState(PWM0_BASE, PWM_OUT_5_BIT, true);
PWMGenEnable(PWM0_BASE, PWM_GEN_2);
}
uint32_t gPWMSample = 0; // PWM sample counter
void PWM_ISR(void)
{
PWMGenIntClear(PWM0_BASE, PWM_GEN_2, PWM_INT_CNT_ZERO); // clear PWM interrupt flag
// waveform sample index
int i = (gPWMSample++) / gSamplingRateDivider;
// write directly to the PWM compare B register
PWM0_2_CMPB_R = 1 + gWaveform[i];
if (i > gWaveformSize) { // if at the end of the waveform array
// disable these interrupts
PWMIntDisable(PWM0_BASE, PWM_INT_GEN_2);
// reset sample index so the waveform starts from the beginning
gPWMSample = 0;
}
}