Understanding a NES controller read program

Alright, so I'm working on interfacing my Arduino to a NES controller. I found this very handy program at http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1254964306
and I understand almost all of it, theres just one line that confuses me:

controller_data = controller_data << 1;
controller_data = controller_data + digitalRead(datin) ;

The second line makes sense, as you're going to get a resultant byte from all of the individual bytes that each consist of 7 0s and a single 1. But what is the first line doing, and why is it doing it?

Any help is appreciated.

  1. controller_data = controller_data << 1;
  2. controller_data = controller_data + digitalRead(datin) ;

The first line: << is a shift right left*. it moves all bits in controllerdata one place to the right left
The second line: adds the outcome of digitalRead() which is a 0 or a 1 (used as a single bit) to controller_data

so after 8 times a byte is filled with 8 readings of digitalRead().

See - << - Arduino Reference - for more info.

  • thanks to bilbo

Not to be picky, but its a shift left. What it means is that your program is reading the digital input, and setting each incoming value to a bit of the byte. The first bit received will go to the MSB and the last will go to the LSB and so on.

For example, the byte in that program starts as 0.
Controller data = 00000000

Say it receives a one, it is written to the LSB to result in Controller data = 00000001
This is then shifted left for: Controller data = 00000010

Say it recieves another 1,it is also written to the LSB to result in Controller data = 00000011
This is then shifted left for: Controller data = 00000110

And so on, until the byte is filled up.

Not to be picky, but its a shift left.

Oops you'r right ! I will update my post

That was the first tutorial I did and it's the only one that people still care about. Long live Nintendo. It took me hours to cobble that stuff together.

I know how you feel. I've written boatloads of stuff on (what I think are) interesting projects, but the only one that got more than a few thousand views was this one http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1268669525 its terribly programmed and doesnt even work anymore and I have since replaced it with this Control an Arduino from a Cellphone (No extra hardware purchase needed) - Exhibition / Gallery - Arduino Forum , but its still the first google result for "cell phone arduino" . Lol.