0

I am trying to work out how this part of this code is working. REF state &= 0X07;

static uint8_t state = 0;
    /*  values for half step             0001, 0011, 0010, 0110, 0100, 1100, 1000, 1001*/
    static const uint8_t HalfSteps[8] = {0x01, 0x03, 0x02, 0x06, 0x04, 0x0C, 0x08, 0x09};
    uint8_t delay;

    do
    {
        if (Count > 0)
        {
            PORTC = HalfSteps[state];   /* drive stepper to select state */
            state++;                    /* step one state clockwise */
            state &= 0x07;              /* keep state within HalfStep table */
            Count--;   

The part after the state++ will increase from start of 0 and I know its resetting to 0 after goes above 7.

But not sure how this is achieved I have read that it basically means.

state = state + 7 but that does not look right.

Any easy explanations would be appreciated.

johnnyh20
  • 71
  • 6
  • It means `state = state & 7;`. – HolyBlackCat Mar 14 '23 at 22:38
  • Does this help? https://stackoverflow.com/questions/276706/what-are-bitwise-operators – Nick ODell Mar 14 '23 at 22:39
  • 1
    Are you familiar with bitwise operators in C? The `&` operator is bitwise-AND. Each bit in the result is a 1 if and only if it is a 1 in both operands. The `&=` operator is just a bitwise assignment operator: `x &= y;` is equivalent to `x = x & y;`. – Tom Karzes Mar 14 '23 at 22:39
  • Your loop is just using the last 3 bits of `state` as a 3-bit counter. It counts from 0 to 7, then goes back to 0 (since 8 & 7 is 0). – Tom Karzes Mar 14 '23 at 22:40
  • Thanks for the assistance I am new to bitwise operators but think I can see Toms 2nd comment answers the question. also Davids answer is correct I Like to understand code before I use it and this had me stumped how it worked. – johnnyh20 Mar 14 '23 at 22:54
  • Hi Phuclv Yes that did help in the past I had used the if statement shown in answer 2 which worked for me. Seeing the &= throw me off so thanks for this. 'if(step > 7) step = 0;' – johnnyh20 Mar 15 '23 at 10:22
  • Hi Nick Yes that was helpful sorry I did not reply earlier. – johnnyh20 Mar 15 '23 at 13:15

1 Answers1

0

The following three lines are all equivalent:

state &= 0x07;
state = state & 7;
state = state % 8;

The effect is to ensure that the state is always less than 8, and also that the state that comes after 7 is 0, not 8.

David Grayson
  • 84,103
  • 24
  • 152
  • 189
  • Thank you David I need to get my head around the use of some of the basic mathematics as I did not learn any of this at school and having retired and wanting to program in C there is so much to take in. Modulo is something new to me. – johnnyh20 Mar 14 '23 at 23:10