官术网_书友最值得收藏!

Dancing LEDs in both directions

Let's create another illusion program where the light will go from USER0 to USER3. Then, instead of starting again from USER0, it travels back in the opposite direction from USER3 to USER0. We will follow the turning on of the LED sequence: USER0 -> USER1 -> USER2 -> USER3 -> USER2 -> USER1 -> USER0, and so on. This will look like the LED is traveling till the edge and then bouncing back. Type the previous danceLEDs.js program as it is. Change the following line in the glowUser3() function:

tempTimer = setTimeout(glowUser0, glowTime);

Replace it with the following line:

tempTimer = setTimeout(glowReverseUser2, glowTime);

Then, insert the following code after the glowUser3() function ends and before the exitProgram() function starts. Save the modified code as danceLEDs2.js and run it. You should see the LED pattern moving from USER0 to USER3 and then back to USER0:

function glowReverseUser2()
{
  b.digitalWrite("USR3",b.LOW);
  b.digitalWrite("USR2", b.HIGH);
  tempTimer =setTimeout(glowReverseUser1,glowTime);
}

function glowReverseUser1()
{
  b.digitalWrite("USR2",b.LOW);
  b.digitalWrite("USR1", b.HIGH);
  tempTimer = setTimeout(glowUser0,glowTime);
}

Program explanation

Two new functions are added: glowReverseUser2() and glowReverseUser1(). When the regular glow sequence goes from USER0 to the USER3 LED, instead of calling glowUser0(), we call the glowReverseUser2() function. So, instead of starting from USER0 LED again, our program takes a reverse direction to glow the USER2 LED. The glowReverseUser2() function calls glowReverseUser1(), which glows the USER1 LED. When the reverse sequence hits the USER0 LED, it will follow the normal USER0 to USER3 sequence again.

This whole program has many small functions. It is necessary because setTimeout() needs a block of code kept in the function to continue after timeout. One could argue that the same result can be achieved by combining similar functions in a single function with few arguments and a switch-case pattern inside. It will reduce the code length but that will hamper the simplicity of our program. We will do it in the next chapter while dancing external LEDs.

主站蜘蛛池模板: 台中市| 平江县| 沁水县| 德化县| 楚雄市| 阳曲县| 铜梁县| 敦煌市| 龙江县| 西平县| 会宁县| 鲜城| 南陵县| 临泽县| 奉贤区| 武功县| 资溪县| 扶绥县| 新邵县| 景德镇市| 北碚区| 比如县| 洛扎县| 新化县| 电白县| 华安县| 如东县| 墨竹工卡县| 策勒县| 江北区| 西乌珠穆沁旗| 渭南市| 永善县| 霞浦县| 贵阳市| 奉贤区| 资中县| 定州市| 团风县| 南京市| 理塘县|