0

I'm working on school project where I use serial 8 DIP switches to light up 8 digital LEDs. I use a shield on my Arduino to press a button and make the bits switch on my screen. For example, the user click on the first DIP switch and the second one. Then the first LED and the second LED will light up. After that, I press a button on my shield and the bits start to shift in the position they are.

My question is how can I make the bits go back to their original values when they reach the the last bit they meet in the direction they are switching. Like a rotation of bits.

Example with rotation: the user lights up the first and third LED and they start to switch when this same user press the button. Then, when the second LED reach the bit 0 it goes back to the bit 7 while the first LED is still at bit 1 etc...

byte G;
byte A = 0b00000001;
char data,newData; `

void modeRotationGauche(void) 
{
    G = (data);
    while (digitalRead(KEY_2) == LOW)
    {
        if ( G == 0)
        {
            G = data;
        }
   
        G = G >> 1;
        delay(200);
        Serial.write(G);
        G = G >> 1;
        delay(200);
        Serial.write(G);
        G = G >> 1;
        delay(200);
        Serial.write(G);
        G = G >> 1;
        delay(200);
        Serial.write(G);
    }

data is being read when the user switch the DIP and then print the value

G is used to switch the bit and if G = 0 it returns to the original data value.

But what I want is to make them rotate not make them teleport to the original value. And I need to do that using an if function for the challenge.

1
  • Sorry, but I could not understand well the problem. Anyway if all you need is a rotate function you can do something like G = ((byte)G >> 1) | ((G&1)?0x80:0);. This way you are shifting the old value and then adding the topmost bit if the lowest one was set. NOTE: this is for an 8-bit variable! If you need a bigger one you'll have to edit the 0x80 value Commented Oct 29, 2015 at 22:08

1 Answer 1

3

This function will rotate value to right by amount bits and return the rotated value. (The 8 is the size of type byte in bits)

byte rotateRight(byte value, int amount) {
    return (value >> amount) | (value << (8 - amount));
}

Replace G = G >> 1; with G = rotateRight(G, 1);.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.