cancel
Showing results for 
Search instead for 
Did you mean: 

What is the fairly common way to implement a flag function?

Carter Lee
Associate III
Posted on September 25, 2017 at 08:52

I'm actually I want to implement some such as a flag function into my code.

But I'm struggling with implementation in c.

What is the fairly common way to implement a flag function?

int trigger =0;

main() {

   while(1) {

   switch (num)

   case0

   case1 : 

trigger = 0

   ..

   case6 : trigger = 1

   

   

   if (trigger==1)

   printf('trigger-on');

   else

   printf('trigger-off');

   

   }

}

As you can see the problem of above is  that if case 6 is activated, then we can see lots of '

trigger-on' printed messages.

But I want this just to do one time with trigger or flag.. 

What is the fairly common way to implement a flag function?

1 ACCEPTED SOLUTION

Accepted Solutions
ColdWeather
Senior
Posted on September 25, 2017 at 09:52

First, what has this question with STM micros issues to do? Well, I think there is a lot of ways to solve this. Anyway you have to introduce some variable that would track your prints:

int last_trigger = -1;   // init to a special value out of 'trigger' range for the very first printout.

...

if (last_trigger != trigger)

{

      // do print

      last_trigger = trigger;

}

View solution in original post

3 REPLIES 3
Posted on September 25, 2017 at 09:34

You forgot the breaks for the cases and the functional block for the entire switch.

Also, after acting on the trigger flag you can turn off the trigger.

int main() {
 while(1) {
 switch (num) {
 case 0:
 break;
 case 1:
 trigger = 0
 break;
 //..
 case 6:
 trigger = 1
 break;
 default:
 break;
 }

 if (trigger == 1) {
 printf('trigger-on');
 trigger = 0;
 } else {
 printf('trigger-off');
 }
 }
}�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?�?

ColdWeather
Senior
Posted on September 25, 2017 at 09:52

First, what has this question with STM micros issues to do? Well, I think there is a lot of ways to solve this. Anyway you have to introduce some variable that would track your prints:

int last_trigger = -1;   // init to a special value out of 'trigger' range for the very first printout.

...

if (last_trigger != trigger)

{

      // do print

      last_trigger = trigger;

}

Posted on September 27, 2017 at 22:37

Unfortunately, the code above would print out 'trigger-off' all the time, also at the next pass after a single 'trigger-on' after the case 6. You have either to track the printouts by an additional flag, as I suggested in my reply before, or to reset the 'trigger' to, say, -1 after printing 'trigger-on' out and to add 'if (trigger == 0)' to print 'trigger-off' out.

OT: what HTML tags to format the source code in the articles?