Trouble in LED dimmer control using 'smooth' control

Hello there..
I´m trying t control the dimmer (or bright)of two leds connected to PWM outputs 2&3 on Arduino MEGA 2560.
On the code below, I use a potentiometer as analog input to A0, with an 'smooth' code (using array).
Using a button, I read and keep the reading at desired moment and use it to compare with further variations
of potentiometer values.
Now... if the differences (error in the sketch) are negative, I want one of them to illuminate gradually the associated PWM/led output while the other output keeps at 0v.
Opposite, if the error goes positve from recorded value, I want the alternative PWM/led output to increase illumination while the other other keeps off at 0v.
My trouble is in the last couple of 'if' subroutines on the sketch.
As you probably noticed I´m not very handy on programming... so, I will appreciate any guidance with this "just to practice" sketch.
Thanks in advance. Also I apollogize for some languaje mistakes

const int numReadings = 10;                                                // smooth value
int pwm1 = 2;                                                              // led 1 output
int pwm2 = 3;                                                              // led 2 output
const int buttonPin = 4;                                                   // typical button sketh with resistor
int readings[numReadings];                                                 // the readings from the analog input
int recordedReading;                                                       // memorized reading when button is pressed
boolean buttonState;                                                       // checks if button is pressed
int index = 0;                                                             // the index of the current reading
int total = 0;                                                             // the running total
int average = 0;                                                           // the average
int inputPin = A0;
void setup()
{
  Serial.begin(9600);                                                      // initialize serial communication with computer       
  for (int thisReading = 0; thisReading < numReadings; thisReading++)      // initialize all the readings to '0'
  readings[thisReading] = 0;         
}
void loop()
{
  total = total - readings[index];                                         // subtract the last reading:
  readings[index] = analogRead(inputPin);                                  // read from the potentiometer
  total = total + readings[index];                                         // add the reading to the total
  index = index + 1;                                                       // advance to the next position in the array             
  if (index >= numReadings)                                                // if we're at the end of the array...
  index = 0;                                                               // ...wrap around to the beginning
  average = total / numReadings;                                           // calculate the average
  Serial.print("Average: ");                                               // send average to....
  Serial.println(average);                                                 // ..serial COM in use
  int buttonState = digitalRead(buttonPin);                                // read buttn state...
  if (buttonState == HIGH)                                                 //... if button is pressed
  {
    recordedReading = average;                                             // establishes the value to be recorded = average
    Serial.print("Recorded: ");                                            // send recorded value to ...
    Serial.println(recordedReading);                                       // ..serial COM in use
  }
  int error;                                                               // checks for the difference (error)....
  error = (average - recordedReading);                                     // ...between existing average and recorded value
  Serial.print("error: ");                                                 // send error to....
  Serial.println(error);                                                   // ..serial COM in use
  if (error <= 0)                                          
  {                                                       
    analogWrite(pwm2, error);                              
    delay(5);                                              
  }                                                       
  if (error >= 0)                                          
  {                                                        
    analogWrite(pwm1, error);                              
    delay(5);                                              
  }
  delay(10);
}

Hi,

You have not really described what the problem is. What happens when the sketch runs?

I spotted a few errors, maybe fixing them will help.

  1. You are sending a negative number to analogWrite(). If you do that you will not get the brightness level you intended. Turn the negative number into positive like this:
analogWrite(pwm2, -error);

or use the abs() function.

  1. Your readings from analogRead() can be up to 1023, but analogWrite() will only accept values up to 255. The error value you are calculating could be over 255, giving an unwanted level of brightness. Maybe use the constrain() function.

  2. When you set the brightness level of one led, do you want the other led to be off? Your sketch is not doing this. If error goes from positive to negative and is exactly zero at some point, it will work. But if error goes from positive to negative without ever being exactly zero, both leds could be on at a low brightness.

Paul

Use

val = analogRead(pin) <<2);

To put the pot value into the range 0 to 255

Hi there...
Thanks for your inputs.
I draw a pic of the hardware..
What I intend is a slow reaction to changes in potentimeter arm after using the button. (that´s why the arrray/averager).
I position the 1K potentiomer at center (500 ohms). Wen loading the sketch the Average reading goes to 500 faster or slower depending on the last delay value.
The error goes gradually to the same value (500 ohms).
Now, the useful part of the sketch....
It begins by pressing the button (error goes to 0 ohms) and set both leds to 0 volts (totally OFF).
From that situation, any variation (let´s say)CW on the pot arm, I try to increase the bright on one of the leds while the other remains OFF. If the potentiometer returns to center that led will respond dimming as the error returns to '0'.
Opposite, if the pot arm goes CCW from center, the other leds will act the same way.
Well... this last portion (bright/dimm) on either side of center position is what I can´t get in order.
This sketch pretends to be a wind direction alert. Wind vanes are always moving around the true wind direction.
I try to set the wind vane pointing to wind in such manner the pot. arm reads +/- 500 ohms. By pressing the button (set to 0 ohms after vane is steady, the next changes will dimm (or brigh) the positive/negative error and associated led .
Sorry again for mistakes on spelling english...
I know there are sophisticated wind artifacts with arduino... but are expensive just to try...
Thanks again

Sorry folks... :roll_eyes:
I follow the recomendations of PaulRB (thanks)...
It works the way I want...
I know this is not the most fancy sketch about wind vanes but, it works (initially) for the final project I have in mind..

No problems pacheco.

I learned to sail at the "Canary Sail" school in St Sebastian de la Gomera. La Gomera is one of my favourite places on the world. From there I have sailed to Tenerife, La Palma and El Heiro.

Paul

Heyy... Nice to see you know these part of the World..
As a matter of fact my project is related with my sailboat... :slight_smile: :slight_smile:
I live in Gran Canaria (Las Palmas) and use to sail around this islands...
The idea is to tie the wind vane with a sort of resistor or encoder on its shaft pointing to wind and at a given moment, at straight course, memorize the pot. reading and use the variations (above or below) to a motor to drive the tiller..
If I get this goal I´ll post it on this thread...

Grumpy_Mike:
Use

val = analogRead(pin) <<2);

To put the pot value into the range 0 to 255

Typo?

Playing with the potentiometer (1K) in the circuit, I found certain conditions where, as mentioned before,
the analogRead exceeds the 255 max value.
the line
val = analogRead(pin) <<2);
I guess is a solution but I´m not sure how to use it, on de code I posted at the beggining...
Any help will be very wellcome..

The error Riva was pointing out is that Mike put an extra ")" after the "<<2".

Mike's solution should work but it may make the circuit less responsive to small errors.

My suggestion (from my first post) was to use the constrain() function:

analogWrite(pwm2, constrain( error, 0, 255));

OK... Thanks PaulRB and Riva...
I change the 'if' statements an the end of original code as follows and got a very steady response delayed the way I need

if (error <= 0)
  {
    analogWrite(pwm1, constrain( -error, 0, 255));
    delay(20);
  }
  if (error >= 0)
  {
    analogWrite(pwm2, constrain( error, 0, 255));
    delay(20);
  }
  delay(50);
}

Thanks a lot again