All submissions

Triangular Wave Generator

Solving Approach

How do you plan to solve it?

 

Code


#define DAC_PIN 25

#define AMP_POT_PIN 34  
#define FREQ_POT_PIN 35 


int amplitude = 128;    
float frequency = 250;  


unsigned long lastPotReadTime = 0;
const unsigned long POT_READ_INTERVAL = 100000;  


int currentValue = 0;   
bool rising = true;     
unsigned long lastStepTime = 0;
long delaySteps = 0; 


int readAvg(int pin, int samples = 5) {
  int sum = 0;
  for (int i = 0; i < samples; i++) {
    sum += analogRead(pin);
  }
  return sum / samples;
}

void setup() {
  Serial.begin(115200);
 
  analogReadResolution(12);
}

void loop() {
  unsigned long currentTime = micros();


  if (currentTime - lastPotReadTime >= POT_READ_INTERVAL) {
    lastPotReadTime = currentTime;

    
    int ampRaw = readAvg(AMP_POT_PIN);
    int freqRaw = readAvg(FREQ_POT_PIN);


    amplitude = map(ampRaw, 0, 4095, 1, 255);
   
    frequency = map(freqRaw, 0, 4095, 1, 500);

   
    delaySteps = 1000000L / (2.0 * amplitude * frequency);
  }

  
  if (currentTime - lastStepTime >= delaySteps) {
    lastStepTime = currentTime;

  
    dacWrite(DAC_PIN, currentValue);

    
    if (rising) {
      currentValue++;
      
      if (currentValue >= amplitude) {
        rising = false;
      }
    } else {
      currentValue--;
 
      if (currentValue <= 0) {
        rising = true;
      }
    }
  }
}

 

Output

Video

Add a video of the output (know more)

 

 

 

 

 

Photo of Output

Add a photo of your hardware showing the output.

 

 

 

 

 

 


 

Submit Your Solution

Note: Once submitted, your solution goes public, helping others learn from your approach!