2

I am working on the atmel programming and I am trying to make a program that has a function that returns a Boolean that is once true and the second time is false that depends on whether is it called before or not like it returns true the first time an the second it returns false and I would make the program like::

if(boolean == true){

//execute the code if the button is pressed for the first time

//switch on a led


}else{

//execute the code if the button is pressed for the second time

//turn off the led

}

the function is like::

bool ledToggle(){

if(function is called for the first time)

return true;

}else{

return false;

}
BenMorel
  • 34,448
  • 50
  • 182
  • 322
user3407319
  • 227
  • 2
  • 10

3 Answers3

4

You can just use a static flag for this, e.g.

bool ledToggle()
{
    static bool state = false;

    state = !state;

    return state;
}
Paul R
  • 208,748
  • 37
  • 389
  • 560
  • Save some memory (that is quite scarce on the average micro controller) by using `usigned char` instead of `int`! It's probably only one byte, but it sums up... – Cu3PO42 Apr 17 '14 at 11:51
  • but this will only work for twice I need a function that works for a lot of times 1-true 2-false 1-true 2-false and so on like maybe resetting the int somehow – user3407319 Apr 17 '14 at 11:52
  • 1
    It would have helped if you had mentioned that in the question - I'll update the answer... – Paul R Apr 17 '14 at 11:53
  • 3
    +1. Oh the joys of the moving spec! Be careful with thread safety though. – Bathsheba Apr 17 '14 at 11:54
3

A static variable within a function remembers its value between calls to the function:

bool ledToggle()
{
    static bool led_is_on = false;

    led_is_on = !led_is_on;
    return led_is_on;
}

That will make the result flipflop between true and false with each call.

RichieHindle
  • 272,464
  • 47
  • 358
  • 399
  • It's a nice answer (and worthy of a +1 for its concision) but I'd disallow it in my code base as it's extremely thread un-safe. These kind of toggle idioms bite hard in MT environments. – Bathsheba Apr 17 '14 at 12:13
  • @Bathsheba: Fair point, but if I was a betting man I'd be putting my money on this microcontroller LED-toggling program being single-threaded. :-) – RichieHindle Apr 17 '14 at 12:25
  • @RichieHindle: wouldn't be allowed on the Mars lander's codebase ;-) – Bathsheba Apr 17 '14 at 12:27
3

If your compiler supports it (C11 with STDC_NO_ATOMICS not defined) then use:

#include <stdatomic.h>

bool ledToggle()
{
    static atomic_int state; // initialised to zero by default
    state ^= 1; // XOR is atomic, state = !state is not atomic.
    return state; // rely on implicit cast to bool
}

This will be thread safe.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483