So, I have an Arduino Uno, with 8 Leds connected to the pins.
Im trying to write a program that will randomly force an LED to blink.
then the program randomly chooses whether or not to go left or right, making the next led blink.
Then it continues on going to either left or right from there.
Making a sequence of 0, 1, 2, 3, 4, leds blink is easy.
But I dont know how to do this, can someone help with the language.
I have 8 leds, 0-7
so if it ever reaches 7, the choices would be 6 or 0.
Is this possible?
And better, how do I do this?
Thanks in advance to any helpful and considerate replies to this.
Well, you have a variable holding which LED is blinking, then when it's tine to change it up you either increment or decrement it. What's the difficulty?
PROTIP: to constrain a number to a range, you typically use the % operator. But this operator does odd things with negative numbers. To manage this, instead of decrementing like so:
define an array of pin numbers corresponding to each LED
choose a random index into the array
choose a random direction, setting a variable to 1 for right or -1 for left
pass each array index, beginning with the one randomly chosen, to a function that blinks a LED
I recommend that you do not use pins 0 and 1 for LEDs, since they are used for serial communication.
Below is some demo code that prints LED pin numbers to the serial port.
const int NUM_LEDS = 8; // total # of leds
// pins for each led, left to right
byte ledPins[] = {
2,3,4,5,6,7,8,9};
void setup()
{
Serial.begin(9600);
// seed random generator
randomSeed(analogRead(0));
}
void loop()
{
// index to first led
int ledIdx = random(0, NUM_LEDS);
// direction: 0 = next, 1 = previous
int ledDirection = random(0,2) ? 1 : -1;
Serial.print("Directions is ");
Serial.println( (ledDirection == 1) ? "right" : "left");
// blink each led
for(byte i=0; i < NUM_LEDS; i++)
{
blink(ledPins[ledIdx]);
// adjust index
ledIdx += ledDirection;
// watch for overflow or negative
if( ledIdx < 0 )
{
ledIdx = NUM_LEDS-1; // wrap to end
}
else if( ledIdx == NUM_LEDS ) {
ledIdx = 0; // wrap to start
} // else
} // for
Serial.println("");
}
void blink(byte pinNum)
{
// print pin number of LED to blink
Serial.print("Blinking ");
Serial.println(pinNum);
}