Using arrays in MC

Discussion in 'Programmer's Corner' started by pujulde, Dec 26, 2014.

  1. pujulde

    Thread Starter Member

    Jul 24, 2013
    95
    1
    1 #include <avr/io.h>
    2 int main(void)
    3 {
    4 DDRB = 0b01111111;
    5 PORTB = 0b00000000;
    6 DDRD = 0b01111111;
    7 PORTD = 0b00000000;
    8 TCCR1B |= 1<<CS10 | 1<<CS11;
    9 int LEDNumber[2];
    10 while(1)
    11 {
    12 if (TCNT1 > 2232)
    13 {
    14 TCNT1 = 0;
    15 PORTB = 1<<LEDNumber[0];
    16 LEDNumber[0] ++;
    17 if (LEDNumber[0] > 6)
    18 {
    19 LEDNumber[0] = 0;
    20 PORTD = 1<<LEDNumber[1];
    21 LEDNumber[1] ++;
    22 if (LEDNumber[1] > 6)
    23 LEDNumber[1] = 0;
    24 }25 }26 }27 }
    Can you explain me the execution of program from line 15. As I understand the LEDNumber[0] is array which's element is increasing and then assigned to the appropriate port. After execution of line 16 the LEDNumber[1], then LEDNumber[2], LEDNumber[3], LEDNumber[4], LEDNumber[5], LEDNumber[6] and then it enter in line 19. Thanks in advance.
     
  2. MrChips

    Moderator

    Oct 2, 2009
    12,447
    3,363
    No.

    There are only two members in the array. This is declared in Line 9.
    There is LEDNumber[0] and LEDNumber[1]. There is no LEDNumber[2], LEDNumber[3]...LEDNumber[6].

    LEDNumber[0] and LEDNumber[1] are containters for values starting at zero.
    These containers are incremented by 1 in Line 16 and Line 21.
    When the values reach 7 the values are reset to 0.
     
  3. pujulde

    Thread Starter Member

    Jul 24, 2013
    95
    1
    Thank's. When the array was declared it was not given some values, yes? And after definition it can accept any values in the range of integers. I was confused because int LEDNumber[2] had not given values. Now I understand. Thanks.
     
  4. MrChips

    Moderator

    Oct 2, 2009
    12,447
    3,363
    It depends on how the compiler is implemented. Some compilers may choose to initialize the variable to zero.
     
    pujulde likes this.
  5. WBahn

    Moderator

    Mar 31, 2012
    17,757
    4,800
    And some may not, which makes this very bad code.
     
Loading...