9 years, 2 months ago.

Colour changer question

Can you explain this code and what it means in terms of the various numbers and codes Thanks

  1. include "mbed.h"

PwmOut r (p23); PwmOut g (p24); PwmOut b (p25);

int main() { r.period(0.001); while(1) { for(float i = 0.0; i < 1.0 ; i += 0.001) { float p = 3 * i; r = 1.0 - ((p < 1.0) ? 1.0 - p : (p > 2.0) ? p - 2.0 : 0.0); g = 1.0 - ((p < 1.0) ? p : (p > 2.0) ? 0.0 : 2.0 - p); b = 1.0 - ((p < 1.0) ? 0.0 : (p > 2.0) ? 3.0 - p : p - 1.0); ; wait (0.01); } } }

Question relating to:

Example program to cycle the RGB LED on the mbed application board through all colours application, Board, rgb

1 Answer

9 years, 2 months ago.

In the future please put <<code>> and <</code>> around code blocks and then use preview in order to ensure any code you post is readable.

? and : are a shorthand version of if/else. e.g.

adult = (age > 18) ? true : false;

is a shorthand way of saying

if (age > 18)
  adult = true;
else
  adult = false;

There have been many internet forum wars over whether using this syntax is a good thing or not. It can make for far more compact code which aids readability, it can also be used to create complete gibberish that is impossible to follow.

The annotated full code is:

#include "mbed.h"

 // define 3 PWM outputs, one for each colour
PwmOut r (p23); 
PwmOut g (p24);
PwmOut b (p25);
 
int main()
{
    r.period(0.001); // set the red PWM period to 0.001s (not sure why the other 2 aren't set) 

    while(1) { // loop forever

        for(float i = 0.0; i < 1.0 ; i += 0.001) {  // i goes from 0 to 1 in steps of 0.001

            float p = 3 * i;                        // p will go from 0 to 3 in steps of 0.003

    // set the red PWM duty cycle (the red LED brightness
            r = 1.0 - ((p < 1.0) ? 1.0 - p : (p > 2.0) ? p - 2.0 : 0.0);   
           // For the first 1/3 of the cycle (p = 0 to 1)     r = 1 - (1-p)    (it ramps from 0 to 1)
           // for the second 1/3 of the cycle (p = 1 to 2)    r = 1 - 0        (it stays at 1 the whole time)
           // for the third 1/3 of the cycle (p = 2 to 3)     r = 1 - (p-2)    (it ramps from 1 to 0)

            g = 1.0 - ((p < 1.0) ? p : (p > 2.0) ? 0.0 : 2.0 - p);
            b = 1.0 - ((p < 1.0) ? 0.0 : (p > 2.0) ? 3.0 - p : p - 1.0);  ;  
            // red and green are the same as the red only shifted by 1/3 of a cycle in each direction.

            wait (0.01);
           // wait for 10ms. So a full cycle will take ~10 seconds. (10 seconds due to the waits plus any calculation time)

        } // end the for loop

    }  // end the while loop

} // end main