SWRMeter/firmware/waveformgenerator.ino

80 lines
1.9 KiB
Arduino
Raw Normal View History

2024-02-11 12:50:31 +01:00
#include "Waveforms.h"
2024-02-11 21:56:13 +01:00
#define PWM_BIT_WIDTH 8
#define PWM_PIN 5 // PWM-Pin für DAC0 auf dem Arduino Nano 328
2024-02-11 12:50:31 +01:00
2024-02-11 21:56:13 +01:00
uint8_t wf_wave0 = 0;
uint8_t wf_pos = 0;
uint16_t wf_freq = 0;
unsigned long wf_sample_us = 0;
unsigned long wf_prevMicros = 0;
2024-02-11 12:50:31 +01:00
bool wf_outputEnabled = true; // Variable to control waveform output state
void initWaveformGenerator()
{
2024-02-11 21:56:13 +01:00
pinMode(PWM_PIN, OUTPUT);
2024-02-11 12:50:31 +01:00
setWaveform(WAVEFORM_SINUS);
// Call the function to set default frequency, here you might want to specify a default frequency
2024-02-11 21:56:13 +01:00
setWaveformFrequency(WAVEFORM_DEFAULT_FREQ_HZ);
2024-02-11 12:50:31 +01:00
}
2024-02-11 21:56:13 +01:00
void setWaveform(uint8_t waveform0)
2024-02-11 12:50:31 +01:00
{
if (waveform0 >= 0 and waveform0 < WAVEFORM_MAXWAVEFORM_NUM)
{
// Set default waveforms
wf_wave0 = waveform0;
2024-02-11 21:56:13 +01:00
} else {
wf_wave0 = WAVEFORM_SINUS;
2024-02-11 12:50:31 +01:00
}
}
2024-02-11 21:56:13 +01:00
void setWaveformFrequency(uint16_t frequency)
2024-02-11 12:50:31 +01:00
{
if (frequency >= 1 and frequency < 8000)
{
2024-02-11 21:56:13 +01:00
wf_freq = frequency;
2024-02-11 12:50:31 +01:00
} else {
2024-02-11 21:56:13 +01:00
wf_freq = WAVEFORM_DEFAULT_FREQ_HZ;
2024-02-11 12:50:31 +01:00
}
2024-02-11 21:56:13 +01:00
wf_sample_us = 1000000UL / ((unsigned long)wf_freq * WAVEFORM_MAX_SAMPLES_NUM);
2024-02-11 12:50:31 +01:00
}
void enableWaveformOutput()
{
wf_outputEnabled = true;
}
void disableWaveformOutput()
{
wf_outputEnabled = false;
}
void pollWaveformGenerator()
{
2024-02-11 21:56:13 +01:00
2024-02-11 12:50:31 +01:00
if (wf_outputEnabled)
{
2024-02-11 21:56:13 +01:00
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, (1 << PWM_BIT_WIDTH)-1);
sample = constrain(sample, 0, (1 << PWM_BIT_WIDTH)-1);
analogWrite(PWM_PIN, sample); // write the selected waveform on DAC0
// analogWrite(PWM_PIN, 128); // write the selected waveform on DAC0
wf_pos++;
if (wf_pos == WAVEFORM_MAX_SAMPLES_NUM) // Reset the counter to repeat the wave
wf_pos = 0;
}
} else {
analogWrite(PWM_PIN, 0);
2024-02-11 12:50:31 +01:00
}
}