0
votes

Here im using the stm32l discovery microcontroller. First i initialize the ports for the gpio ports for the leds and the user button.

I have it working now and the little program i have now makes the led blink. Every time you press the button the waiting time gets longer making the led blink longer. the problem now is that as soon as the waiting time exeeds 4 seconds or more its to hard for the microcontroller to notice the button press. Is there a way to make it that it always notices a button press

int main(void) {
        char *RCCp = (char*) 0x40023800;
        int *PAp = (int *) 0x40020000;
        int *PBp = (int *) 0x40020400;

        // RCC Config
        *((int*) (RCCp + 28)) |= 0x3f;
        *((int*) (RCCp + 32)) |= 1;

    // Pin config
        *PBp = 0x5000;
        *PAp = 0x0000;

        int speed = 100000;

            int i = 0;
            while (1) {
                while (i++ < speed); // Waiting time
                *(int*) (0x40020414) ^= 0xC0; 

                i = 0;

                if ((*(int*) (0x40020010) & 0x0001) != 0x0) {

                    speed = speed * 2;

                    if (speed > 400000) {

                        speed = 100000;
                    }

                }

            }


        return 0;
    }
1
You might want to find out what interrupts are and how to use themJens Wirth

1 Answers

3
votes

One small step forward is to poll the switch status within your busy-wait loop. Like this:

        int i = 0;
        while (1) {
            bool wasSwitchClosedThisPeriod = false;
            while (i++ < speed) {
                // Poll the switch to see if it is closed.
                if ((*(int*)(0x40020010) & 0x0001) != 0) {
                    wasSwitchClosedThisPeriod = true;
                }
            }

            *(int*) (0x40020414) ^= 0xC0; 

            i = 0;

            if (wasSwitchClosedThisPeriod) {

                speed = speed * 2;

                if (speed > 400000) {

                    speed = 100000;
                }

            }

        }

But there is still a lot of room for improvement. For example, you may want to debounce the switch. The switch data register should be volatile, i.e. *(int volatile *)(0x40020010UL). And using interrupts could make the code more flexible, efficient and even allow you to put the microcontroller to sleep while it waits (conserving power). If the GPIO input pin can be configured as an interrupt then you wouldn't need to poll the switch. And if there's a hardware timer available then you could configure it to interrupt when it's time to change the LED.