NerdKits - electronics education for a digital generation

You are not logged in. [log in]

NEW: Learning electronics? Ask your questions on the new Electronics Questions & Answers site hosted by CircuitLab.

Microcontroller Programming » DIP Arithmetic Exercise - Binary and Decimal Numbers

May 25, 2013
by Kami
Kami's Avatar

I have done the DIP Arithmetic project in the Nerdkit manual and have a few questions about this part:

  a1 = (PINC & (1<<PC0)) >> PC0;
  a2 = (PINC & (1<<PC1)) >> PC1;
  a3 = (PINC & (1<<PC2)) >> PC2;

  b1 = (PINC & (1<<PC3)) >> PC3;
  b2 = (PINC & (1<<PC4)) >> PC4;
  b3 = (PINC & (1<<PC5)) >> PC5;

      lcd_home();
  lcd_write_string(PSTR("Adding: "));
  lcd_write_int16((a1<<2) + (a2<<1) + a3);
  lcd_write_data('+');
  lcd_write_int16((b1<<2) + (b2<<1) + b3);
  lcd_write_string(PSTR("        "));

  lcd_line_two();
  lcd_write_string(PSTR("Equals: "));
  lcd_write_int16(  ((a1<<2) + (a2<<1) + a3)  +  ((b1<<2) + (b2<<1) + b3) );
  lcd_write_string(PSTR("        "));
  1. Assuming PC0, PC1 & PC2 were all high, in the lcd write line where a1 to a3 are added, how does the software know it is adding binary 1+2+4 = 7, rather than decimal 1+10+100 = one hundred and eleven?

  2. Why 'lcd_write_int16' and not 'lcd_write_int8'?

  3. Is there a reason why the arithmetic is done in the lcd write line and not added in a variable before hand?

  4. Why keep writing over the results on the lcd which is why the spaces are written at the end? Why not just clear screen before each new write to the lcd?

Thanks in advance.

May 25, 2013
by JimFrederickson
JimFrederickson's Avatar

My Answers to your questions...

1 - You see the line:
(a1<<2) + (a2<<1) + a3)
This is taking the value of I/O Line a1 and shifting it twice.
Effectively doing (a14) + (a22) + a3
Customarily CPU's are binary machines so shifting to the left 1
binary digit position is equivalent to multiplying by 2. (right is divide)

2 - I think using 'lcd_write_int16' is lew of it's 8 bit counter part is a choice.
16 bits are more flexible, can hold larger values, so that is probably why.

3 - Again, I think this was a choice. Alot of people like to merge things together.
For me I like to split them apart so that it's more step oriented.

4 - Often times when you have programs that display more than on bit of information.
In that case it can become wasteful to rewrite the entire screen each time
when only one field is changed. So it is a good habit to get into to treat
writes a "fields". That is why the spaces are there. (Of course if you
modifying most of the screen fields then clearing makes more sense.)

Kind of short answers, not really covering all of the permutations, but hopefully what you were looking for.

May 29, 2013
by Kami
Kami's Avatar

Thanks Jim, that clears it up for me!

Post a Reply

Please log in to post a reply.

Did you know that electric fields behave differently in different materials? Learn more...