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