Wiring Forum
http://wiring.org.co/cgi-bin/yabb/YaBB.pl
Programming Questions & Help >> Syntax >> Loop through outputs problem
http://wiring.org.co/cgi-bin/yabb/YaBB.pl?num=1210134411

Message started by William on 05/07/08 at 04:26:51

Title: Loop through outputs problem
Post by William on 05/07/08 at 04:26:51
Heya folks

Using my actionscript knowledge I am trying to randomly switch off and on a number of outputs. Heres the code:


int LEDPin6 = 23;
int LEDPin5 = 22;
int LEDPin4 = 21;
int LEDPin3 = 20;
int LEDPin2 = 19;
int LEDPin1 = 18;
void setup(){
 pinMode(LEDPin1, OUTPUT);
 pinMode(LEDPin2, OUTPUT);
 pinMode(LEDPin3, OUTPUT);
 pinMode(LEDPin4, OUTPUT);
 pinMode(LEDPin5, OUTPUT);
 pinMode(LEDPin6, OUTPUT);
}

void loop(){
 int i;
 for(i=0; i<=6; i++) {
   int x;
   int y;
   x = random(5000);
   y = random(5000);
   digitalWrite (LEDPin+i, HIGH);
   delay (x);
   digitalWrite (LEDPin+i, LOW);
   delay (y);
   if (i>6){
     i=0;
   }
 }
}

but does not work, do I have to code this the long way instead or is there something basic I am missing. Obviously this is written in a procedural manner, should this be written in an oop manner?

Title: Re: Loop through outputs problem
Post by barragan on 05/07/08 at 06:11:25
yes, this is wrong the variable LEDPin doesn´t exist,
what you could do is this:


int LEDPins[] = {10, 19, 20, 21, 22, 23};

for(int i = 0; i<6; i++) {
 digitalWrite(LEDPins[i], HIGH);
 delay(x);
 digitalWrite(LEDPins[i], LOW);
 delay(y);
}

I guess this might help you to understand how variables work and how to iterate through the pins.

Title: Re: Loop through outputs problem
Post by William on 05/07/08 at 10:13:42
Yes! quite so, thank you. I hope this helps others out there.

Title: Re: Loop through outputs problem
Post by Titus on 05/08/08 at 06:23:42
Dear  William,

An int uses way more space then other variables.
If you are using pins, or values that won't change during your program, please use:

# define LEDpin 10
# define LEDpin 11
etc

This uses less memory, and the values can never be changed accedentely

Titus

Wiring Forum » Powered by YaBB 2.5 AE!
YaBB Forum Software © 2000-2010. All Rights Reserved.