# 3-bit Counter - Using solely (nested) for loops

6 views (last 30 days)
Hans123 on 5 Apr 2021
Edited: Hans123 on 6 Apr 2021
Hi there,
I am trying to write a way to create an 3 column 8-bit RGB array to capture all 15 million+ possible colors - without storing the values, dynamically on an arduino (end code will be in C). I want to approach this problem by scaling down and using a language I am comfortable with - i.e. MATLAB.
So I want to understand a very rudimentary 3 bit counter, 2^3 = 8 rows, 3 columns - without using MATLAB's inbulit flipud, or dec2bin functions.
Only nested for loops.
What is the most logical way of approaching this problem? There will be a pattern of numbers always recurring in a sequence set by the column value as shown below - is it smart to utilize this sequence? I would really appreciate any pointers!
**I believe this problem (with regards to the RGB matrix) is documented, however, I want to exhaust all possible methods to do it by myself - before looking up resources
4 2 1 repitition (2^col)
______
0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 1
1 1 0
1 1 1
DGM on 5 Apr 2021
Okay, I misunderstood what you're trying to do. I thought you were trying to make a 3-bit counter by incrementing three unique 1-bit numbers. You're actually dealing with columns of 8-bit numbers. Sorry. I guess that makes more sense.
I guess it's be better to call it a 3-digit base-256 counter ... but they aren't really "digits"

DGM on 5 Apr 2021
Edited: DGM on 6 Apr 2021
I guess the simple way would be something like this:
% i'm going to assume your counter goes [R G B]
% i.e. B is the least significant term of the counter
for R=uint8(0:255)
for G=uint8(0:255)
for B=uint8(0:255)
% do whatever you want with R,G,and B
[R G B]
end
end
end
Although I have no idea how that will compile. It might be naive of me to try to coax it into only using 8 bits.
That would get you a sequence, but it's not really a counter that can be incremented externally. For that, you could make a function:
function [R G B]=testcounter(R,G,B,n)
if B<(n-1)
B=B+1;
else
B=0;
if G<(n-1)
G=G+1;
else
G=0;
if R<(n-1)
R=R+1;
else
R=0;
end
end
end
end
Testing it like so:
B=0;
G=0;
R=0;
% counter base
% using a small number is good for demo
% set this to 256 for uint8, obviously
n=3;
for k=1:(n^3+1) % show counter roll over
[R G B]
[R G B]=testcounter(R,G,B,n);
end
Hans123 on 6 Apr 2021
this is an absolute genius method; I can't thank you enough.
I wish I can develop this thought process - took me 2 days of thinking to figure out I need help!
Cheers!

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by