Here's an example code for a PSOC DDS (Direct Digital Synthesis) waveform generator:
CCopy code
#include <project.h>
// Waveform settings
#define SAMPLING_RATE 48000 // Hz
#define FREQUENCY 1000 // Hz
#define AMPLITUDE 1.0 // 0.0 to 1.0
#define WAVEFORM_LENGTH 256 // Samples
// DDS settings
#define DDS_CLOCK_FREQ 100000000 // Hz
#define DDS_PHASE_ACC_WIDTH 32
#define DDS_PHASE_ACC_SCALE 4294967296.0 // 2^DDS_PHASE_ACC_WIDTH
#define DDS_PHASE_INCREMENT ((FREQUENCY * DDS_PHASE_ACC_SCALE) / DDS_CLOCK_FREQ)
// Lookup table for waveform samples
uint8 waveform[WAVEFORM_LENGTH] = {
0, 24, 49, 73, 97, 120, 142, 164, 184, 203, 220, 235, 247, 255, 260, 260,
255, 247, 235, 220, 203, 184, 164, 142, 120, 97, 73, 49, 24, 0, 0, 0, 0,
// ... (omitted for brevity)
0
};
// Variables for tracking DDS phase and output sample
uint32 dds_phase_acc = 0;
uint8 output_sample = 0;
int main(void)
{
CyGlobalIntEnable; /* Enable global interrupts. */
// Set up the output pin
Waveform_Output_Enable_Write(1); // Enable output
Waveform_Output_Start(); // Start output
Waveform_Output_SetDriveMode(Waveform_Output_DM_STRONG);
// Set up the timer interrupt for sampling the waveform
uint32_t interrupt_period = DDS_CLOCK_FREQ / SAMPLING_RATE;
Waveform_Timer_Start();
Waveform_Timer_WritePeriod(interrupt_period - 1);
Waveform_Timer_EnableInt();
for(;
{
// Do nothing, DDS output is generated in the interrupt handler
}
}
CY_ISR(Waveform_Timer_ISR)
{
// Increment DDS phase accumulator
dds_phase_acc += DDS_PHASE_INCREMENT;
// Compute waveform sample from DDS phase accumulator
uint8_t waveform_index = (dds_phase_acc >> (DDS_PHASE_ACC_WIDTH - 8)) % WAVEFORM_LENGTH;
output_sample = (uint8_t)(waveform[waveform_index] * AMPLITUDE);
// Write output sample to output pin
Waveform_Output_Write(output_sample);
}
Here's how the code works:
- First, we define some constants for the waveform settings, such as the sampling rate, frequency, amplitude, and waveform length.
- We also define constants for the DDS settings, such as the clock frequency, phase accumulator width, phase accumulator scaling factor, and phase increment.
- We create a lookup table for the waveform samples. This example code uses a 256-sample lookup table for a sine wave, but other waveforms could be used as well.
- We define variables for tracking the DDS phase accumulator and the output sample.
- In the main() function, we enable global interrupts and set up the output pin for the waveform generator.
- We set up a timer interrupt to sample the waveform at the desired sampling rate. The interrupt period is calculated based on the DDS clock frequency and the desired sampling rate.
- In the interrupt handler, we increment the DDS phase accumulator by the phase increment value. We then compute the index into the waveform lookup table based on the phase accumulator value and scale the sample by the