LED Bits

Computational Thinking, Electronics, MSU MAET

Here’s my interpretation of the Count the Dots activity. Sorry for the shakeycam, my production assistant had gone to bed.

The program was created using Python on a Raspberry Pi, and the LED lights were controlled with an Arduino. The binary value was passed from the Pi to the Arduino via serial over USB.

To show that I resisted the temptation of using Python’s built in ability to change a Unicode value to binary, here’s the function I created to convert an integer value to a string that contained the binary value:

def convert_to_binary(asciival):
  binaryval = ""

  for n in xrange(7,-1,-1):
    bitval = 2**n
    if (asciival - bitval) >= 0:
      asciival -= bitval 
      binaryval += "1" 
      writeval = chr(n)
      ser.write(writeval) # send signal to light LED
    else:
      binaryval += "0"

  return binaryval

Pretty terrible variable names now that I look at it again. I am sure there are faster ways of doing this, but this algorithm mimics the way I could do it using pencil and paper: try subtracting the largest bit place value, 2^8, from the number. If the difference is zero or greater, that bit is a ‘1’, otherwise a ‘0’. Continue with the next bit to the right until the value of bits subtracted is equal to the value of the number.

I haven’t programmed in a long time, so when I ran into a unexpected design flaw, it required a bit of thinking. I originally set it up so that it would read one key press at a time and show the binary value as I typed, but when it came to write out my birthday, I realized it would have to handle multidigit numbers. I think running into problems like these is where the creative aspect of programming takes place. Getting it to work as I wanted it to was very satisfying in the end, and that’s the feeling I want to elicit in students I serve.

2 thoughts on “LED Bits

  1. This is awesome! I got a Raspberry Pi last year, but I’ve not used Python on it much…most automating JavaScript and other web-based languages. Very cool implementation and use of the LED’s as well. I’m feeling jealous…

    1. Thanks! Getting into Python and trying to get the Pi and Arduino to work together was something I wanted to try out for a while, so this was a good chance to do so. When I get home I’ll update the post with the source code. It’s pretty bad, but will show how straightforward Python makes some things. Definitely a bit of transition coming from C/Java or even JS though in terms of syntax. I don’t think we’re the only ones interested in using the Raspberry Pi/programming/etc. in MAET so if there’s a chance to share some knowledge, I think we could get something going.

Leave a Reply

Your email address will not be published. Required fields are marked *