Can someone please explain how this code example works?

I understand most of it, but the bit with the HEX and colors loose me. I understand sending different PWM values to the LED to get it to be either red or green, but what the setColor(col) function is doing does not make any since.

I made it work with a simple red on/off and green on/off function, but i would really like to understand what i’m missing.

for example, using just high and low voltages seems to get it done with out whatever the heck was happening with 0xhex in the first example. See lesson 6 for example.

this was how i managed to get lesson 1 working with things that i understood.

Talking about the Python code, setColor receives a 16 bit value where the 1st 8 bits represents how much Red you’d like to see - a value between 0x00 meaning no red, and 0xff meaning full red, and values in between give shades of red. The 2nd 8 bits do the same for Green.

It then shifts the pattern to the right by 8 bits, causing the Green bits to fall off, and the Red bits to land up in the right hand low order position, effectively isolating and getting just the amount of red that we want.

Then it takes the input pattern again and masks it with an AND operation using 0x00ff as the mask. The bits of the input pattern that align with ff are preserved and the bits that align with 00 are wiped out leaving us with just the amount of green that we want.

The map function then takes those values, which in decimal range from 0-255 and scales them to range from 0-100 which is the range chosen and required for the PWM output pins that are going to drive the LED colours.

Hope that helps?

1 Like
You can use setColor() to control the brightness value of the red and green LEDs by PWM value, thus presenting a mixed color, such as pink.

1 Like

Well that explains that perfectly!
I did not realize the program was supposed to do more than just flip between red and green. The fact that it’s blending between red and green makes since now!

I think knowing that it’s mixing colors coupled with the explanation of what happens in each part of the hex string 0xRrgG was the magic that made it click.

Thank you all for the quick reply!!
Context is king!