Hello,
im trying to make my CR servo to rotate when green LED is on and stay still when its OFF... at the moment it rotates only when LED starts and then it stop and doesnt rotates anymore... my code is:
#include <Servo.h>
Servo servoLeft;
Servo servoRight;
int ledGreen = 13;
int ledRed = 12;
int val = 0;
void setup() {
servoLeft.attach(9);
servoRight.attach(10);
servoLeft.write(90);
servoRight.write(90);
pinMode (ledGreen, OUTPUT);
pinMode (ledRed, OUTPUT);
pinMode (8, INPUT);
}
void loop() {
digitalWrite(ledGreen, HIGH);
delay(10000);
digitalWrite(ledGreen, LOW);
delay(1000);
digitalWrite(ledRed, HIGH);
delay(10000);
digitalWrite(ledRed, LOW);
delay(1000);
}
void loop2(){
val = digitalRead(ledGreen);
if (val == HIGH) {
servoLeft.write(180);
servoRight.write(180);
} else {
servoLeft.write(90);
servoRight.write(90);
}}
Also, i was testing my program on an online simulator, here is the link: https://123d.circuits.io/circuits/1213102-college-project-test1
Are you perhaps hoping that the loop2() function will run automatically after the loop() function ? If so then you need to think again. The loop2() function will not run unless you call it.
Thanks for the code tags, but the loop2() function is still not being called so will not run. As written the servos will both move to 90 because of the write()s in setup() and they will stay there with the LEDs flashing.
As @UKHeliBob pointed out, your loop2() function never gets called.
I think you are trying to make sure that each servo is turning as long as its corresponding LED is lit. I would recommend doing that in a non-blocking fashion, getting rid of the delay() functions entirely. You can try to use a millis() timer, something like this(untested) code:
@BulldogLowell you are right, i'm using continuous rotation servo.
Thank you for your help, so far on a simulator your code works fine, I will test it on my arduino as soon as i can and I will leave message here with the result.