Hi! I am working on a project where I want to be able to fade LEDs at the same time as running servo motors on my Arduino Uno. I am very new to coding and have self-taught so far. I finally have figured out the servo part, minus some tweaking I plan to do in the future. I now want to try and add LED fading while they are running. The code I have now, the LEDs just stay on continuously without any fade. Any help or advice would be greatly appreciated! (Side note: I know that delay use in both the LED fade and servo sweep would not be able to accomplish what I want to happen. Is it possible to still use delay on the servos I have running? I currently have four servos attached.)
Below is part of my code, I didn't include all of it as it is just different parts of only the servo motors at different angles.
#include<Servo.h>
Servo servo1;
Servo servo2;
Servo servo3;
Servo servo4;
int value, value2 ;
int ledpin = 10; // light connected to digital pin 10
int ledpin2 = 11; // light connected to digital pin 11
long time=0;
int periode = 30000;
void setup() {
servo1.attach(9);
servo2.attach(8);
servo3.attach(7);
servo4.attach(6);
// put your setup code here, to run once:
}
void loop() {
{
time = millis();
value = 128+127*cos(2*PI/periode*time);
value2 = 128+127*cos(2*PI/periode*time);
analogWrite(ledpin, value); // sets the value (range from 0 to 255)
analogWrite(ledpin2, value2); // sets the value (range from 0 to 255)
}
for (int i = 0; i < 180; i++) {
servo1.write(i);
delay(50);
servo2.write(i);
delay(30);
servo3.write(i);
delay(40);
servo4.write(i);
delay(60);
}
for (int i = 180; i > 0; i--) {
servo1.write(i);
delay(50);
servo2.write(i);
delay(30);
servo3.write(i);
delay(40);
servo4.write(i);
delay(60);
}
for (int i = 0; i < 20; i++) {
servo1.write(i);
servo3.write(i);
delay(10);
}
for (int i = 20; i > 0; i--) {
servo1.write(i);
servo3.write(i);
delay(10);
}
First thing to do is get away from using blocking for loops and delay() if you want to do things at the same time.
If you are using for loops to control the speed of the servos, the MobaTools servo library allows speed and position control in the background so you can instruct the servo to move to a position at whatever speed and go about your other business while the servo(s) does so.
The MobaTools library also has LED control that may be of interest.
And, contrary to what is often shown on the web, do not power servos from the Arduino. Doing so is a recipe for frustration. A 4 AA cell is a good supply.