mindthump icon

Rotate Array in C (LEDs)

mindthump | PRO | 08/29/21 07:37:33 PM UTC (Edited) | 0 ⭐ | 1785 👁️ | Never ⏰ | []
C |

1.08 KB

|

None

|

0 👍

/

0 👎

#include <stdio.h>
 
const int strip_len = 42;
char strip[strip_len];
const char colors[] = {'R', 'W', 'B', '\0'};
//const char colors[] = {'R', 'O', 'Y', 'G', 'B', 'I', 'V', '\0'};
int num_colors = sizeof(colors) / sizeof(colors[0]) - 1;
 
void show_strip();
 
void init_strip();
 
void rotate();
 
int main() {
    init_strip();
    show_strip();
    // Rotate once for each slot (LED)
    for (int j = 0; j < strip_len - 1; j++) {
        rotate();
        show_strip();
    }
    printf("\n");
    return 0;
}
 
void rotate() {
    char last;
    last = strip[strip_len - 1];
    for (int i = strip_len - 1; i >= 0; i--) {
        strip[i] = strip[i - 1];
    }
    strip[0] = last;
}
 
void show_strip() {
    for (int n = 0; n < strip_len; n++) {
        printf("%c", strip[n]);
    }
    printf("\n");
}
 
void init_strip() {
    int chunk_len = strip_len / num_colors;
    for (int q = 0; q < num_colors; q++) {
        for (int p = 0; p < chunk_len; p++) {
            int led = (q * chunk_len) + p;
            strip[led] = colors[q];
        }
    }
}

Comments