 # Loop length confusion

Hey everyone! I am getting an SNES controller to work via Arduino and using this code. Effectively, the only difference between the NES controller and the SNES controller is that there’s sixteen pulses on the clock and the data generated is sixteen bit.

Anyhow, everything works great and I almost completely understand how the code works except for one thing. Excerpted from the code I linked above, from inside the controllerRead() function:

``````digitalWrite(latch,HIGH);
delayMicroseconds(2);
digitalWrite(latch,LOW);

for (int i = 1; i <= 7; i ++) {
digitalWrite(clock,HIGH);
delayMicroseconds(2);
controller_data = controller_data << 1;
controller_data = controller_data + digitalRead(datin) ;
delayMicroseconds(4);
digitalWrite(clock,LOW);
}
``````

Now, when the latch is given a HIGH pulse, it stores the state of the buttons. Why is there a digitalRead before the loop and why is the loop going from 1-7? My only idea is that the first read sets a baseline for the data that the loop then finishes by bitshifting, but I’m not entirely sure.

The explanation for the code states that “the first bit becomes the most significant bit,” so if my interpretation of it is correct, is that a peculiarity of this code or is that how this sort of situation is generally handled (one read in first and a datasize-1 loop after)? Thanks!

controller_data becomes 0 or 1 with the first read from the whatever is on pin datin.
It then shifts it left one bit ( <<1) and the next read goes into the lowest bit position.
So the 7 more reads then create an entire byte from the data on pin datin.

Why is there a digitalRead before the loop and why is the loop going from 1-7?

One bit is read, and controller_data is assigned a value.

Then, 7 times, the value in controller_data is moved one bit to the left, and a new value stored in the 0 bit, by adding 0 or 1 to the existing number.

The explanation for the code states that "the first bit becomes the most significant bit,"

The first bit read in is stored in the right-most bit. It is then shifted left 7 times, to increasingly more significant (numerically higher) bit positions.