microsoft / pxt-adafruit

Microsoft MakeCode editor for Adafruit Circuit Playground Express
https://makecode.adafruit.com
Other
81 stars 77 forks source link

Light Counter sample code incorrect #1202

Closed Jaqster closed 2 years ago

Jaqster commented 2 years ago

Incorrect sample code for the Light Counter project - https://github.com/Microsoft/pxt-adafruit/blob/master/docs/examples/counter.md

Reported by a customer: The sample code for the counter counts 0 1 2 3 4 5 6 7 8 9 00 01 02 03 04 05 06 07 08 09 10 11 12 ... 98 99 0 1 2 ...

Doing so only makes partial sense if the LED indices for the tens digit are re-assigned to be 1 to 10 instead of 0 to 9. But that doesn't make sense when counting past 99 when the 10s digit becomes 2 digits (10), wrapping from 109 to 0 and continuing from there. The code below is my suggestion of a replacement that keeps the feature of leading-zero blanking and has some other style changes -- Button A and B are similar and simpler, 99 is a high limit similar to 0 being the low limit, and colors I prefer.

let isTen = false let isDigit = false let cntGT9 = false let tens = 0 let digits = 0 let count = 0 function render() { music.playTone(262 + count * 50, music.beat(BeatFraction.Quarter)) digits = count % 10 tens = (count - digits) / 10 cntGT9 = count > 9 light.clear() for (let i = 0; i <= 9; i++) { isDigit = i == digits isTen = i == tens if (cntGT9 && (isTen && isDigit)) { light.setPixelColor(i, 0x0000ff) } else if (cntGT9 && isTen) { light.setPixelColor(i, 0x00ff00) } else if (isDigit) { light.setPixelColor(i, 0xff0000) } } } input.buttonB.onEvent(ButtonEvent.Click, function () { if (count < 99) { count += 1 } render() }) input.buttonA.onEvent(ButtonEvent.Click, function () { if (count > 0) { count += -1 } render() }) render()