Search code examples
cmicrocontroller

How to return back when the button is clicked?


When I first press the button, it performs the first function, on the second press, it performs the second task when the third press I want to return and perform the same first function.

void blinkcursor(void);
int count = 0;

void blinkcursor(void)
{   
  label:
    if (button == 1) {                 //button pressed
        if (count == 0) {
            count++;
            set_cursor_position (1, 2);
            lcd_cout(0x0f);                      //cursor blink
            button = 0;
        }
        else if(count == 1) {
            lcd_cout(0x0c);                       //blink off
            button = 0;
        }
        goto label;
    } 
}

Solution

  • You didn't say much about the overall structure of your program, so I am just going to assume that you have some main loop running that regularly checks the state of the button, performs any necessary debouncing, and sets button to 1 whenever it detects that the button was pressed. I will also assume that the cursor is not blinking by default, and that the button is only used to toggle the blinking of the cursor.

    Now just add a call to the following function in your main loop:

    bool blink_enabled = false;
    
    void update_blink(void)
    {
      if (button) {
        // Button was pressed.
        if (blink_enabled) {
          // Turn off blinking.
          lcd_cout(0x0c);
          blink_enabled = false;
        }
        else {
          // Turn on blinking.
          set_cursor_position(1, 2);
          lcd_cout(0x0f);
          blink_enabled = true;
        }
        button = 0;
      } 
    }
    

    (You might need to add #include <stdbool.h> at the top to get the bool type.)