What's causing my microcontroller LED program to stop working?

I would have thought that you would need a loop around your code -

while(1)
{

    if (ip == 1){
       op = 0;
       wait (1.0);
       op = 1;}
    else {
       op = 1;}
}

Before you have chance to press the button you code will have finished and exited. You need the while to keep the if statement repeatedly running.


#include "mbed.h"

DigitalIn ip(D7);
DigitalOut op(D8);

int main() {
    if (ip == 1){
        op = 0;
        wait (1.0);
        op = 1;
    }else{
        op = 1;
    }
    // and now the program ends? What to do?
}

The processor executes the instructions sequentially. It starts with a jump to main() from within the mbed library initialisation code of DigitalIn and DigitalOut.
Then performs the comparison ip == 0, runs the instruction within the {} and then main() ends... no more instructions... What does it do?

It could reset due to finding illegal operands in the empty flash memory. Or it will could hang in a fault handler and blink SOS like mbeds do. This depends on how this is implemented, and will probably go beyond you right now.
But if you're curious you can research ARM Fault Handling, or find out where main() is actually called from.

Now, how to fix this?

int main() {
    // Add a while(1) infinite loop
    while(1){
        if (ip == 1){
            op = 0;
            wait (1.0);
            op = 1;
        }else{
            op = 1;
        }
    }
    // Program never gets here
}

As correctly mentioned by others, a loop would allow your code to run repeatedly. However, there is a built-in way to do this for Arduino without the need for a while loop. This is done by the loop function - its applicability to your problem is dependent on whether you use the Arduino IDE.

It should look something like this:

#include "mbed.h"

DigitalIn ip(D7);
DigitalOut op(D8);

void setup() {
    // any code before loop is run
}

void loop() {
    if (ip == 1){
        op = 0;
        wait (1.0);
        op = 1;
    }else{
        op = 1;
    }
}

Your main function is now hidden and is only added to your program when compiled. Here is a good discussion on this: http://forum.arduino.cc/index.php?topic=379368.0

Tags:

Led

Nucleo