DIY: Generating Ramp/Sawtooth from a PWM signal
/*Code for prodcing a Sawtooth wave from PWM*/
int pwm_pin = 9;
int brightness = 0;
int upramp(int brightness)
{
while(1)
{
brightness+=5;
delay(100);
analogWrite(pwm_pin, brightness);
if(brightness>250)
{
digitalWrite(pwm_pin,LOW); // Statement:1 for sudden drop in output HIGH ---> LOW
brightness=0;
break;
}
}
return brightness;
}
// the setup routine runs once when you press reset:
void setup() {
// declare pin 9 to be an output:
pinMode(pwm_pin, OUTPUT);
}
// the loop routine runs over and over again forever:
void loop() {
brightness=upramp(brightness);
}
This code is pretty straightforward; I am not going to explain it. (Do let me know in case of any query in the comment section below).
After our PWM signal is set up, we need to look for a decent Low Pass filter; I tested both passive RC filters and active sallen key filter.
First, let’s try the RC filter:
RC filter:
Oscilloscope settings: roll mode, dc coupling on both inputs |
The yellow signal corresponds to the PWM wave while Green is of sawtooth-like wave |
circuit |
One can also use this wonderful online design tool (with cutoff frequency=490hz) to predict resistance/capacitance values.
As one can easily make out that the output is closer to what we want, but still, it’s not perfect!! Hmm…..
Now let’s try sallen Key active LPF
Sallen-Key LPF
one can easily predict values I used using http://sim.okawa-denshi.jp/en/OPseikiLowkeisan.htm , just by specifying the cut-off frequency.
Below is the comparison of the output of sallen key and RC filter:
Yellow:- Output of Sallen Key LPF, Green:- Output of RC LPF |
fallen
Output values of Sallen-key LPF |
Output values of RC LPF |
Actual circuit |
But, before leaving, just have a look at fall time in case of RC LPF and Sallen Key LPF. Also, the contrast between Vmax and Vmin in both cases.
Apart from the crisp output, Sallen Key can also be configured to provide gain to the output signal, thus providing an added advantage.
Do let me know in case of any query/feedback, would love to hear one!
If you like it, don’t forget to share it.
At last, Feedback???