Reputation: 856
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.
Upvotes: 0
Views: 1608
Reputation: 75062
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);
.
Upvotes: 3