# Arduino frequency and duty cycle with 2 pots

#### 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() {
bool succes = SetPinFrequencySafe(9, frequency);
}

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

#### ericgibbs

Joined Jan 29, 2010
11,122
hi B,
Do you mean the PWM frequency or the Mark/Space ratio of the PWM signal.?
E

#### 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.
• 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.

#### 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);
}