Search code examples
arduinoarduino-unoarduino-ide

How to write code to make the LED’s flash in the following sequence?


How to write code like this sequence? What is the meaning of 4 decimal? For this, we had to add a delay in the code

led_Pin_1 1 0 0 0 
led_Pin_2 0 1 0 0 
led_Pin_3 0 0 1 0 
led_Pin_4 0 0 0 1 

my code, It is working. But I need to convert this code to the above sequence?

int led_Pin_1 = 11;
int led_Pin_2 = 10;
int led_Pin_3 = 9;
int led_Pin_4 = 8;

void setup() {
  pinMode(led_Pin_1, OUTPUT);
  pinMode(led_Pin_2, OUTPUT);
  pinMode(led_Pin_3, OUTPUT);
  pinMode(led_Pin_4, OUTPUT);
}

void loop() {
  digitalWrite(led_Pin_1, HIGH);
  delay(200);
  digitalWrite(led_Pin_2, HIGH);
  delay(200);
   digitalWrite(led_Pin_3, HIGH);
  delay(200);
   digitalWrite(led_Pin_4, HIGH);
  delay(200);
  digitalWrite(led_Pin_1, LOW);
  delay(300);
   digitalWrite(led_Pin_2, LOW);
  delay(300);
   digitalWrite(led_Pin_3, LOW);
  delay(300);
   digitalWrite(led_Pin_4, LOW);
  delay(300);
}

If a change like this, what is that meaning

LED1 1 0 0 0
LED2 1 1 0 0 
LED3 1 1 1 0
LED4 1 1 1 1

Solution

  • I recommend you to use Array.

    First, you need to create an array for your LEDs. Then create a function to set the proper value for this array. After that, you can simply assign desired values inside a loop.

    A good to use array is that you can change the size easily without modifying all codes.

    // Number of LEDs
    #define ARRAY_SIZE 4
    
    //Pin definitions
    #define LED_PIN_1 11
    #define LED_PIN_2 10
    #define LED_PIN_3 9
    #define LED_PIN_4 8
    
    // Array that holds led pin numbers
    const int led_pins[ARRAY_SIZE] = {LED_PIN_4, LED_PIN_3, LED_PIN_2, LED_PIN_1};
    
    // a temp array to hold led values
    int led_array_value[ARRAY_SIZE] = {0};
    
    void display(int *input)
    {
        for (int i = 0; i < ARRAY_SIZE; i++)
        {
            digitalWrite(led_pins[i], input[i]);
        }
    }
    
    void setup()
    {
        for (int i = 0; i < ARRAY_SIZE; i++)
        {
            pinMode(led_pins[i], OUTPUT);
        }
    }
    
    void loop()
    {
        for (int i = 0; i < ARRAY_SIZE; i++)
        {
            // reset all leds to 0
            memset(led_array_value, 0, sizeof(led_array_value));
            // turn on current led
            led_array_value[i] = 1;
            display(led_array_value);
            delay(500);
        }
    }