This example is the same as the first simple example but with added code to allow the left button to mute the beeping and the right button to change the maximum range. The on start block is introduced to initialise some variables include two arrays.
The three maximum range distances are stored in the
rangelist array with some associated colours in
huelist (0 is red, 85 is green, 170 is blue in this HSV model).
rangeindex is used to select the current range from
rangelist. The first element in an array in MakeCode is 0, in other languages this may be 1.
The loop is similar to the first example but with the addition of two
if blocks to deal with buttons
A (left) and
B (right) and a more sophisticated condition for beeping which now uses the same range as graphing and constrains the frequency between 100Hz and 8kHz.
The check for
button A uses a common subtraction technique to toggle between the two volume values, 0 and 128.
button B looks more complicated but is only adding 1 (incrementing) the
rangeindex and then returning to the first element if it has gone past the end of the array. The code flashes all the NeoPixels the
pixelhue colour for 1 second to indicate to the user which range has been selected, e.g. green for 100cm.
There is a subtle but important difference between the code for the two buttons. The first uses was pressed and the second uses is pressed.
was pressed checks for any press since the last check but
is pressed only checks as the block is executed. In this case the code before the
if blocks executes quickly hence everything loops frequently allowing the use of the instantaneous
is pressed. Holding down either button for a few seconds will reveal a difference in behaviour relating to this.
MakeCode also has an on block which is an alternative method for coding for buttons. The volume mute could also have been implemented using a boolean value and controlled using set volume although the CPX default level sounds like 20 rather than 128. It is common in computer languages for there to be more than one way to achieve the same goal.