sherzaad:
currently if this is all of your code, you are constantly updating analogWrite. a more sensible approch would be to updating the pwm only if the Vinput value changes. something like this maybe:
(Compiles, NOT tested!)
#define PWM 9
#define FEEDBACK A5
int previous_Vinput = 0;
void setup() {
pinMode(9,OUTPUT);
}
void loop() {
int Vin = analogRead(FEEDBACK);
int Vinput = map ( Vin, 0, 1023, 0, 120);
if (Vinput <= 50){
digitalWrite(PWM, HIGH);
}
else if (Vinput != previous_Vinput) //update analogWrite current PWM value only it Vinput is different
{
previous_Vinput = Vinput;
int pwm = (50 * 255)/Vinput;
pwm = constrain(pwm, 1, 255);
analogWrite(PWM, pwm);
}
delayMicroseconds(1000); //optional arbitrary delay to slow things down a bit
}
However I do not think that will give you what you expect either as your 'feedback' is not checked against a 'target value' at the moment.
IMHO you need to implement some form of control loop mechanism where by 'Vin' would be your 'output target value' and 'feedback' your actual output value, then use those 2 value to adjust the 'pwm' as an attempt to maintain the 'output target value'.
hope that helps...
Thanks a lot for your help but the problem still exists, even after applying the code you wrote, as well, what do you mean adding another reference ???
#define TOP 1299 // Fosc = Fclk/(N*(1+TOP), Fosc = 20kHz, Fosc = 16MHz
int pwm=255;
int feedback = A5;
int PWM = 9 ;
void setup() {
pinMode(feedback, INPUT);
pinMode(PWM, OUTPUT);
TCCR1A = 0; //reset the register
TCCR1B = 0; //reset the register
TCNT1 = 0; //reset the register
TCCR1A |= (1<<COM1A1); // set output at non inverting mode
TCCR1A |= (1<<WGM11); // selecting Fast PWM mode
ICR1 = TOP; // setting frequency to 20KHz
TCCR1B |= (1<< CS10)|(1<<WGM12)|(1<<WGM13); //Timer Starts
// delay for compensating the hardware transient time with software
}
void loop() {
int Vin = analogRead(feedback);
float Vinput = map (Vin, 0,1023,0,120);
if (Vinput <= 50)
{
digitalWrite(PWM,HIGH);
}
else if (Vinput > 50)
{
int k = (50)/Vinput;
int pwm = k*255 ;
pwm = constrain(pwm, 1, 1023);
analogWrite(PWM,pwm);
}
}