Strage behavour, shouldn't be hard to figure out...

Thread Starter

dannybeckett

Joined Dec 9, 2009
185
Hi guys -

I am writing some code that involved bit shifting, but I am getting strange outputs from my microcontroller. Save me explain whats going on, I will share my test code and results with you.

Rich (BB code):
#include <htc.h>
#define _XTAL_FREQ 8000000
__CONFIG (FOSC_XT & WDTE_OFF & PWRTE_ON & MCLRE_ON & CP_OFF & CPD_OFF & BOREN_OFF & IESO_OFF & FCMEN_OFF & LVP_OFF & DEBUG_OFF);

void initDigitalOut() {
    PORTA = PORTB = PORTC = PORTD = 0;
    TRISA = TRISB = TRISC = TRISD = 0;
    ANSEL = ANSELH = 0;
}

test0() {
    int temp;
    int y = 0xFF;                // 11111111
    PORTB = y;
    __delay_ms(1000);
    for (int x = 0; x < 8; x++) { 
        y = y >> 1;
        PORTB = y; 
        __delay_ms(1000);
    }
}

test1() {
    int y = 0x88;                // 10001000
    PORTB = y;
    __delay_ms(1000);
    for (int x = 0; x < 8; x++) { 
        y = y >> 1;
        PORTB = y; 
        __delay_ms(1000);
    }
}

test2() {
    int y = 0x8888;                // 1000100010001000
    PORTB = y;
    __delay_ms(500);
    for (int x = 0; x < 16; x++) { 
        y = y >> 1;
        PORTB = y; 
        __delay_ms(500);
    }
}

test3() {
    int y = 0x7888;                // 0100100010001000
    PORTB = y;
    __delay_ms(500);
    for (int x = 0; x < 16; x++) { 
        y = y >> 1;
        PORTB = y; 
        __delay_ms(500);
    }
}

test4() {
    unsigned int y = 0x7888U;    // 0100100010001000
    PORTB = y;
    __delay_ms(500);
    for (int x = 0; x < 16; x++) { 
        y = y >> 1;
        PORTB = y; 
        __delay_ms(500);
    }
}

test5() {
    unsigned int y = 0x8888;    // 1000100010001000
    PORTB = y;
    __delay_ms(500);
    for (int x = 0; x < 16; x++) { 
        y = y >> 1;
        PORTB = y; 
        __delay_ms(500);
    }
}

void main() {
    initDigitalOut();
//    test0();    // Worked fine.
//    test1();    // This worked fine. Bits shifted along nicely and the last loop outputted a fully-off PORTB.
//    test2();    // This worked fine until the most significant 1 appeared... It left a trail of 1s behind it!
//    test3();    // This produced a pattern of 0111100010001000, traversing PORTB, the trailing LEDs were all off this time though.
//    test4();    // Same as test3. Any combination of U and unsigned didn't address this issue.
    test5();    // Worked as expected. U suffix didn't seem to make a difference, unsigned did though. Tried all combinations of both.    
}
I found the answer to the 'trailing' LEDs problem (unsigned variable) but I cant seem to figure out test4()'s behaviour. Anyone shed any light to the matter?

Thanks

Dan
 
Last edited:
Top