Control LEDs & Servo Simultaneously

Hello,

I have an integrated art/electronics project. I’m looking to move a painted cardboard spaceship across a painted outer space canvas using a servo WHILE SIMULTANEOUSLY having LEDs twinkle as stars. As I have it written now, the spaceship moves across the canvas from start position to end position, THEN the stars twinkle (kind of), and then it returns.

How can I make the servo FOR structure run at the same time as the LEDs twinkle FOR structure. Lastly (to make it more complicated) I want the two FOR structures to run simultaneously only if a spectator walks in front, so it’s all running within the IF structure of a motion sensor.

Below is the sketch I have now. Any help is greatly appreciated! Thank you!

/*Starship Painting

GOAL: When a viewer steps in front of the painting,
use a servo motor to move a painted cardboard spaceship
across a painted outer space canvas
while LEDs twinkle in the background.*/

//Servo Library & Variables
#include <Servo.h>
Servo myservo;

//Motion Sensor Variables
int pos = 0;
int sensor = 2;
int val = 0;

//LED Variables
int ledPin = {
5, 6, 9, 10, 11};
int ledState[5];
long randNumber;

void setup() {
//Servo & Motion Sensor Setup
myservo.attach(3);
pinMode(sensor, INPUT);
Serial.begin(9600);

//LED Setup
for (int i=0; i<=4; i++){
pinMode(ledPin*, OUTPUT);*
}
randomSeed(analogRead(0)); *
for (int i=0; i<=4; i++){ *
ledState = random(20, 201);
_
}
_
}
void loop() {
//Read Motion Sensor and Take Action if Motion
*val = digitalRead(sensor); *
if (val == HIGH){
* //Slowly Move Spaceship Across Canvas*
* for (pos = 0; pos <= 120; pos += 1) {*
* myservo.write(pos); *
* delay(100); *
* }*

* //Twinkle LEDs*
* for (int i=0; i<=4; i++){ *
analogWrite(ledPin_, ledState*);
randNumber = random(-100, 101);
ledState += randNumber;
if (ledState > 200) {
ledState = 200;
}

if (ledState < 10) {
ledState = 10;
}

}

delay(100); *_

* //Quickly Return Servo to Start Position*
* for (pos = 120; pos >= 0; pos -= 1) {*
* myservo.write(pos); *
* delay(1); *
* }*
* }*
}
[/quote]

Hopefully, you can now see why we ask you to use code tags when posting code.

Lighting or extinguishing a LED takes virtually no time at all.
Changing the commanded position of a servo takes virtually no time at all.

Have a look at the blink without delay example in the IDE and see if gives you a clue as to how to achieve what you want to do.

This

  for (pos = 120; pos >= 0; pos -= 1) { 
  myservo.write(pos);             
  delay(1);                      
  }

is a very long-winded version of this myservo.write (0);