Arduino frequency and duty cycle with 2 pots

Thread Starter

Bogdan.m

Joined Apr 20, 2019
46
Hello everyone, i am using a simple sketch for a PWM signal, However every time i need to change the frequency i have to upload a new sketch, is there a way to set the frequency using a 2nd pot ?

Code:
#include <PWM.h>
int32_t frequency = 25000;

const int Pin = 9;
int PWM = 0;
void setup() {
  InitTimersSafe();
  bool succes = SetPinFrequencySafe(9, frequency);
}

void loop() {
  PWM = map(analogRead(A0), 0, 1023, 0, 255);
  analogWrite (Pin, PWM);
  delay(100);
}
 

Thread Starter

Bogdan.m

Joined Apr 20, 2019
46
The PWM frequency. I found that using this library, the frequency can be changed really easy, but idk if it can be changed by a pot.
 

Alec_t

Joined Sep 17, 2013
11,744
If A0 is being use to set the duty-cycle then you could use the pot and another analog port to set the frequency. Does that Arduino PWM library allow frequency to be set to an arbitrary value, or just to preset values?
 

djsfantasi

Joined Apr 11, 2010
6,962
The simple answer is yes, you can use a second pot to adjust the PWM frequency out of the Arduino.

You will need to use two Arduino commands.
  • analogRead()
  • map()
Read the descriptions of these commands on the Arduino reference pages, to make sure you use the correct data types.

Connect the 2nd pot’s wiper to an analog input pin; the ends to ground at +5V. Read the value of the input pin using analogRead(). It should return a value from 0 to 1023.

Map this input value to the desired range for the PWM frequency, using the map() function.

That’s all you should have to do.
 

Thread Starter

Bogdan.m

Joined Apr 20, 2019
46
to make things more easy (for me at least) i have split the code into 2 halves, they work independently, but when i put them together my duty cycle pot only works from 0 to about 2% and then goes to full on.

Code:
#include <PWM.h>

void setup() {
}
void loop() {

int32_t frequency = map(analogRead(A1), 0, 1023, 0, 25000);
  InitTimersSafe();
  SetPinFrequencySafe(9, frequency);
  delay (50);
 
  analogWrite (9, map(analogRead(A0), 0, 1023, 0, 255));
  delay(50);
}
 
Top