// https://forum.arduino.cc/t/what-is-this-code-for-msbfirst-lsbfirst-bit-shifting-doing/1056898/6
// This version uses left and right shift of the 8-bit loop variable rather
// than a count value. This allows using the loop variable as a mask against
// the outgoing data and saves using a separate mask variable. This doesn't
// realize any real advantage because the compiler adds a 16-bit loop counter
// anyway in addition to the shifted value.
// The code drives eight CC leds via a 74HC595 register.
const uint8_t clockPin = 2;
const uint8_t latchPin = 3;
const uint8_t dataPin = 4;
const uint8_t pButton = A0;
uint8_t pButtonLast;
const uint8_t lsbfirst = 1;
uint8_t number;
void setup() {
Serial.begin(115200);
pinMode(pButton, INPUT_PULLUP);
pinMode(2, OUTPUT);
pinMode(3, OUTPUT);
pinMode(4, OUTPUT);
digitalWrite(latchPin, LOW);
}
void loop() {
// shift the loop variable and use it directly ( no bit shifting on the data variable )
static byte button;
number = random(255);
button = digitalRead(pButton);
if (button == LOW && pButtonLast == HIGH) {
// shiftout(dataPin, clockPin, 1, number);
shiftout(dataPin, clockPin, 0, number);
Serial.println(number);
}
pButtonLast = button;
delay(10);
}
void shiftout(uint8_t dataPin_, uint8_t clockPin_, uint8_t bitOrder, uint8_t val)
{
byte i;
digitalWrite(latchPin, LOW);
if (bitOrder == lsbfirst) {
for (i = 1; i != 0; i <<= 1) {
digitalWrite(dataPin, (val & i) ? HIGH : LOW);
digitalWrite(clockPin_, LOW);
digitalWrite(clockPin_, HIGH);
}
}
else
for ( i = 128; i != 0; i >>= 1) {
digitalWrite(dataPin, (val & i) ? HIGH : LOW);
digitalWrite(clockPin_, LOW);
digitalWrite(clockPin_, HIGH);
}
digitalWrite(latchPin, HIGH);
}