SWRMeter/firmware/waveformgenerator.ino

107 lines
2.3 KiB
C++

#include "Waveforms.h"
uint8_t wf_wave0 = 0;
uint8_t wf_pos = 0;
uint16_t wf_freq = 0;
uint8_t wf_dutyCycle = 0;
unsigned long wf_sample_us = 0;
unsigned long wf_prevMicros = 0;
bool wf_outputEnabled = true; // Variable to control waveform output state
bool wf_pwm_needs_disabling = true;
void initWaveformGenerator()
{
pinMode(PWM_PIN, OUTPUT);
setWaveform(WAVEFORM_SINUS);
// Call the function to set default frequency, here you might want to specify a default frequency
setWaveformFrequency(WAVEFORM_DEFAULT_FREQ_HZ);
setWaveformDC(0);
analogWrite(PWM_PIN, 0);
}
void setWaveform(uint8_t waveform0)
{
if (waveform0 >= 0 and waveform0 < WAVEFORM_MAXWAVEFORM_NUM)
{
wf_wave0 = waveform0;
} else {
// Set default waveforms
wf_wave0 = WAVEFORM_SINUS;
}
}
void setWaveformFrequency(uint16_t frequency)
{
if (frequency >= 1 and frequency < WF_FREQ_MAX_HZ)
{
wf_freq = frequency;
} else {
wf_freq = WAVEFORM_DEFAULT_FREQ_HZ;
}
wf_sample_us = 1000000UL / ((unsigned long)wf_freq * WAVEFORM_MAX_SAMPLES_NUM);
}
void setWaveformDC(uint8_t dc)
{
wf_dutyCycle = dc;
}
void enableWaveformOutput()
{
wf_outputEnabled = true;
}
void disableWaveformOutput()
{
wf_outputEnabled = false;
}
bool isWaveformEnabled()
{
return wf_outputEnabled;
}
void pollWaveformGenerator()
{
if (wf_outputEnabled)
{
if (wf_wave0 != WAVEFORM_DUTYCYCLE)
{
unsigned long currentMicros = micros(); // Aktuelle Zeit abrufen
if (currentMicros - wf_prevMicros >= wf_sample_us)
{
wf_prevMicros = currentMicros;
uint16_t sample = map(waveformsTable[wf_wave0][wf_pos], 0, 0xfff, 0, PWM_MAX_VALUE);
sample = constrain(sample, 0, PWM_MAX_VALUE);
// TODO write the selected waveform on DAC0
analogWrite(PWM_PIN, sample);
wf_pos++;
if (wf_pos == WAVEFORM_MAX_SAMPLES_NUM) // Reset the counter to repeat the wave
wf_pos = 0;
}
} else {
// WAVEFORM_DUTYCYCLE
if (analogRead(PWM_PIN) != wf_dutyCycle)
analogWrite(PWM_PIN, wf_dutyCycle);
}
if (!wf_pwm_needs_disabling)
wf_pwm_needs_disabling = true;
} else {
if (wf_pwm_needs_disabling)
{
analogWrite(PWM_PIN, 0);
wf_pwm_needs_disabling = false;
}
}
}