Side-to-side pattern
Moving patterns can be incredibly hypnotic, and they can achieved with some simple clever coding with CodeBug. Lots of programming relies on manipulating numbers and it can be extremely powerful way of doing things.
Let’s start with a simple moving pattern that moves from one side of the screen to the other. Create a new python program file and give it a sensible name such as:
myFirstAnimatedPattern.pyIn your program, first import and initialise the CodeBug tether module:
import codebug_tether
c = codebug_tether.CodeBug()Previously you typed out each command to set a row, including the row number and its value, however they can be controlled programmatically with generated values for the row, as this saves typing a long sequence especially with animated patterns that have lots of commands to send.
You will want your animated pattern to repeat forever, so you can hypnotise your friends. To do this use a while loop that is always true.
while True:
for i in range(0,5):
val = 0b00001
for j in range(0,5):
c.set_row(i,val)
val=(val*2)The first iteration of this for loop sets the first LED on the row, and then timeses the row value by 2 to shift the bit, in the next iteration, the row is set to this new value.
You should then perform a sleep to see the effect.
time.sleep(.05)Save and run this code.
This pattern is pretty cool, but it’s a bit jittery as it only goes from one side to the other, but not back again, so it looks like it resets. Let’s fix this!
To make the pattern reverse, you need to repeat your previous for loop, but with a couple of adjustments. Write this new code inside your while loop, outside of your first for loop . If you reverse the range of this new for loop, it will start with the last row, thus reversing the direction the pattern moves in.
for i in reversed(range(0,5)):Instead of starting the row value at 1 (0b00001 in binary) and timesing it by 2 each time, you should instead start with 16 (0b10000 in binary) which has the last LED of the row on and all the others off. In Python, you can set a variable with the binary value by preceding the value with a ‘0b’. If you then divide by 2 each time, the LED pattern will move across the row in the other direction.
val=0b10000
for j in range(0,5):
c.set_row(i,val)
val=int((val/2))
time.sleep(.05)Again, save and run your code. Pretty cool huh?
With structure like this, you can then make your pattern more complex. Try putting in a set_col after each set_row command, with the same values and run it again.
It’s amazing how as little as two lines of code can change a pattern or program in general!