Converting decimal to BCD
<p>I'm working on an assignment currently that uses a microcontroller and a circuit to display a decimal in binary, through LED's. I have to use three push buttons: one to increment, one to decrement, and the last to reset. I have my wiring and configuration complete. My code on the other hand has some glitches that I cannot fix with only an intro to C class under my belt. I am using Code Composer. Problem number one: My counter on the "Tens" section(MSB) does not stop at 9 but rather begins to display binary 10-15. The first four bits are the ones(right) and the second four bits, tens(left) ex: <code>1010 0001</code> but the max value is <code>1001 1001</code>. Problem number two: starting from zero if I decrement the value, the counter displays 95 rather than 99.
ex: starting from <code>0000 0000</code> decrement displays <code>1001 0101</code>. I tried using an if statement to make a condition for MSB to stop if greater than ten but the code doesn't run. Pretty much any modification I did to my code prevents it from working properly.</p>

<pre><code>#include &lt;msp430.h&gt;

unsigned int dec2bcd(unsigned int num);
void delay(void);

int main(void) {
WDTCTL = WDTPW | WDTHOLD;    // Stop watchdog timer

P1DIR = 0xFF;
P2DIR = 0xF0;
unsigned int c;
unsigned int count = 0x00;

while(1){
    if((P2IN &amp; BIT0) == BIT0){
        count++;
        c = dec2bcd(count);
    }

    else if((P2IN&amp;BIT1) == BIT1){
        count--;
        c = dec2bcd(count);
    }

    else if((P2IN&amp;BIT2) == BIT2){
        count = 0x00;
        c = dec2bcd(count);
    }

    delay();
    P1OUT = c;

}

}

unsigned int dec2bcd(unsigned int num)
{
    unsigned int ones = 0;
    unsigned int tens = 0;
    unsigned int temp = 0;

    ones = num%10;
    temp = num/10;
    tens = temp&lt;&lt;4;
    return (tens + ones);
}

void delay(void)
{
    volatile unsigned int i, j;
    for(i=10000; i&gt;0; i--)
    {
        for(j=3; j&gt;0; j--){
    }
}
}
</code></pre>