Having trouble programming random if then statement

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.

Always show us what sketch you have so far so we can see what you have tried.

.

Have you read:
https://www.arduino.cc/en/Reference/Random

If a variable was min = 0 and max = 1, then if the value is 0 you decrement if 1 you increment.

.

I hope you have current limit resistors as well?

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:

x = (x-1) % NUMBER_OF_LEDS;

, which won't work, use

x = (x+NUMBER_OF_LEDS-1) % NUMBER_OF_LEDS;

CrossRoads:
I hope you have current limit resistors as well?

Is that a statement or a question? Looks like a statement to me...

The way I would do this is:

  • 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);

}