1
votes

I'm trying to write a simple program in C that turns a row of LED lights OFF when I press a button. I'm very new to both embedded devices and using bitwise operators and I can't figure out what I'm doing wrong.

I'm using a Romeo board with an Amega328p which is hooked up to an I/O kit board where the pins connect to the LEDs and push buttons seperately.

Romeo Schematic

I/O Tainer Board Schematic: enter image description here

The pins have DDRx PORTx and PINx settings.

I've connected pins D2-D7 to JP3_1-6 for the LEDs (I can see this part works)

I've connected pin D10 (PB2) to JP2_5 for the button (problem part)

I've connect the GNDs & VCCs on both boards to each other.

Here is my code:

void main() 
{
    DDRD =  0b11111100;         // open all registries to be used
    PORTD = 0b11111100;         // set all LEDs ON to start

    DDRB =  0b00000000;         // set as input
    PORTB = 0b00000100;         // set PB2 pull up resistors

    if((PINB & 0b00000100)==0)  // if buttons pressed
    { 
        PORTD = 0b00000000;     // turn all lights off
    }
}

When I push the button nothing happens. I don't think it's the board because it doesn't matter what switch I use.

Any help or direction in solving this would be appreciated. I think it's code and not how I'm hooking things up but I'm a newbie so I could be wrong.

1
What is the other side of the button connected to?afic
Also what is the value of the Pull up disable(PUD) bit in the MCUCR?afic
I'm not quite sure what you mean. I've connect in D10 (PB2) to JP2_5...according to the schematic I think the other side connects to a ground. I don't know what a PUD or MCUCR is? I've been told that I have to set my PORT to 1 b/c it's a pull up resistor.user9409360
Cool, I know enough now to write an answer now.afic
The Pull up disable bit turns disables all GPIO pull ups. You should read through chapter 14 of ww1.microchip.com/downloads/en/DeviceDoc/… which is the data sheet for this micro-controller. The MCUCR is a GPIO register explained in section 14.4.1. You should keep a copy of this data sheet handy when working with this board.afic

1 Answers

2
votes

What is happening is that the if statement is ran once(probably before you even press the button), and then main returns. To fix this you need to run the if statement inside of a while loop. Something like:

void main() 
{

    DDRD =  0b11111100;         // open all registries to be used
    PORTD = 0b11111100;         // set all LEDs ON to start

    DDRB =  0b00000000;         // set as input
    PORTB = 0b00000100;         // set PB2 pull up resistors

    while(1)
    {
        if((PINB & 0b00000100)==0)  // if buttons pressed
        { 
            PORTD = 0b00000000;          // turn all lights off
        }
        //TODO: set LEDs on button release?
    }
}

I do not know what happens when main returns on your micro-controller. A common thing is for main to be re-ran.