Write into array with encoder button

Hi, I am tinkering with the encoder example and I have the following problems.

I want to keep the output_value between 0 and 3, and somehow it counts to 4, and when decrementing, it starts at -1 instead of 3.
(in the increment section: if output_value > 3, output_value = 0
in the decrement section: if output_value < 0, output_value = 3)

the other problem is that I cant manage to invert the values in the array,
using the encoder button.

I googled this, but I cannot find the specific answer.

beat is an array of [4] {1, 1, 1, 1 }
which is meant to be the gate sequence.
output_value is the number created by the encoder.

if(encoder.RisingEdge())
{

        if (beat[output_value] = 1)
        {
        beat[output_value] = 0;
        }
        if(beat[output_value] = 0)
        {
        beat[output_value] = 1;
        }
        hw.PrintLine("Beat:\t%d", beat[output_value]);   
    }

thanks!

This makes code MUCH more readable.

‘the encoder example’ could also be more specific.

The biggest problem I see is this:
if (beat[output_value] = 1)
That should be ==

thank you, this helped a lot.

I also found out that the second case should be “else”.

And for the incrementing bit, I just had the serial monitor in the wrong place,of course it must come after doing the cases.

I can now program my patterns just fine :wink:

A simpler way to invert the value, without if or else:
beat[output_value] = ! beat[output_value];

This is common idiomatic C/C++, though one might argue that it’s unobvious.

My favourite way is:

beat[output_value] = 1 - beat[output_value];

… but it’s more “dangerous” :slight_smile:

I must say, I would never have thought of that. I’ve been a C programmer for about 35 years, professionally.
Another way, even less obvious:
beat[output_value] ^= 1;