Hi,
I am testing the pot controlled pwm output, only the duty cycle changed when vary the potcyc, the frequency doesn't change when very the potfre, why?
Thanks
Adam
const int pwmPin = 3; // assigns pin 12 to variable pwm
const int potcyc = A0; // assigns analog pot input A0 to vary the cyc of pwm
const int potfre = A1; // assigns analog pot input A1 to vary the cfrequency of pwm
int c1 = 0; // declares variable c1
int c2 = 0; // declares variable c2
void setup() // setup loop
{
pinMode(pwmPin, OUTPUT);
pinMode(potcyc, INPUT);
pinMode(potfre, INPUT);
}
void loop()
{
c2 = analogRead(potcyc);
c1 = 1024 - c2; // subtracts c2 from 1000 ans saves the result in c1
digitalWrite(pwmPin, HIGH);
delayMicroseconds(c1);
digitalWrite(pwmPin, LOW);
delayMicroseconds(c2);
int value = analogRead(potfre);
value = map(value, 0, 1023, 0, 255);
analogWrite(pwmPin, value);
delayMicroseconds(40);
}
You are trying to do software PWM and hardware PWM on the same pin. Hardware PWM won't let you change pitch so you should try all-software PWM like this:
const int pwmPin = 3; // assigns pin 12 to variable pwm
const int potcyc = A0; // assigns analog pot input A0 to vary the cyc of pwm
const int potfre = A1; // assigns analog pot input A1 to vary the cfrequency of pwm
void setup() // setup loop
{
pinMode(pwmPin, OUTPUT);
// Don't use pinMode() with analogRead()
}
void loop()
{
float dutyCycleVal = analogRead(potcyc) / 1024.0;
int delayVal = map(analogRead(potfre), 0, 1024, 2000, 0); // delay in
digitalWrite(pwmPin, HIGH);
delayMicroseconds(delayVal * dutyCycleVal); // The ON part of the cycle
digitalWrite(pwmPin, LOW);
delayMicroseconds(delayVal * (1.0 - dutyCycleVal)); // The OFF part of the cycle
}
Why in earth would you want to do this?
I suspect you don’t understand how PWM works.
The simplest way to change the speed is to use the prescaller values, that gives corse control of frequency. For fine control of frequency you also need to change the threshold count register inside the timers that generate the PWM, but that means you can not have full control over the duty cycle and hence the speed of your motor.
A simple way to change the speed of PWM with a pot is to use the Tone library, if that is what you want to do.
void setup() {
DDRB|= 2 ; // Set digital pin 9 (PB1) to an output ;
TCCR1A = _BV(COM1A1) | _BV(WGM11); // Enable the PWM output OC1A on digital pins 9
TCCR1B = _BV(WGM13) | _BV(WGM12) | _BV(CS12); // Set fast PWM and prescaler of 256 on timer 1
ICR1 = 62499; // Set the PWM frequency to 1Hz: 16MHz/(256 * 1Hz) - 1 = 62499
OCR1A = 625; // Set the duty-cycle to 10%: 62499 / 10 = 6249
}
i think you can change Registers according to analogRead value
The Arduino Paltform provides analogWrite(arg1, arg2) function to create known frequency PWM signals at the following DPins (Fig-1) of Arduino UNO. arg1 of the function refers to the DPin and arg2 refers to the duty cycle.