Hello!
What I want is to have 8 randomly chosen pins turning on for a random amount of time (time taken from an array of times) and turning off for a random amount of time (time taken from an array of times.
Unfortunately what I have is serial, where we are always waiting for the delay to finish before moving on to the next operation. I have read this tutorial here but can't seem to get mine to work: http://www.arduino.cc/en/Tutorial/KnightRider
I'm very rusty in coding and was never very good to begin with, so I'm willing to learn. Here's my code:
const byte pinArray[] = {2, 3, 4, 5, 6, 7, 8, 9};
int depthArrayOn[] = {1000,2000,1000,500,700,1000,3000,600};
int depthArrayOff[] = {1000,2000,4000,8000,1000,4000,5000,2000};
int count = 0;
int timer;
int on, off;
int depthOn (int timeOn){
on = depthArrayOn [random (0,7)];
return on;
}
int depthOff (int timeOff){
off = depthArrayOff [random (0,7)];
return off;
}
void setup() {
Serial.begin(9600);
for (count=0; count <=8; count++){
pinMode (pinArray[count], OUTPUT);
}
}
void loop() {
int balloonOn, balloonOff;
int countOn = depthOn(balloonOn);
int countOff = depthOff(balloonOff);
for (count=0;count <= 8;count++) {
digitalWrite(pinArray[random (0,7)], HIGH);
delay (countOn);
digitalWrite(pinArray[random (0,7)], LOW);
delay (countOff);
}
}
The KnightRider example is for a "Larson Scanner" (named after Glen Larson, producer of Knight Rider). The LED's scan back and forth. Your code seems to be about blinking different LEDs in repeating ON/OFF patterns with different ON and OFF times. The Knight Rider code won't help much with that. You need a time value for each LED to remember when the current ON or OFF time started. Here is how I would write it:
const int LEDCount = 8;
const byte LEDPins[LEDCount] = {2, 3, 4, 5, 6, 7, 8, 9};
const int OnTimes[LEDCount] = {1000, 2000, 1000, 500, 700, 1000, 3000, 600};
const int OffTimes[LEDCount] = {1000, 2000, 4000, 8000, 1000, 4000, 5000, 2000};
unsigned long timeStarts[LEDCount];
void setup() {
Serial.begin(9600);
for (int i = 0; i < LEDCount; i++) {
pinMode(LEDPins[i], OUTPUT);
}
}
void loop() {
unsigned long currentTime = millis();
for (int i = 0; i < LEDCount; i++) {
if (digitalRead(LEDPins[i])) {
// Pin is ON
if (currentTime - timeStarts[i] >= OnTimes[i]) {
// ON time done
digitalWrite(LEDPins[i], LOW); // Turn LED off
timeStarts[i] += OnTimes[i]; // Time it was supposed to be turned off
}
} else {
// Pin is OFF
if (currentTime - timeStarts[i] >= OffTimes[i]) {
// OFF time done
digitalWrite(LEDPins[i], HIGH); // Turn LED on
timeStarts[i] += OffTimes[i]; // Time it was supposed to be turned on
}
}
}
}