volatile structs

Go To Last Post
3 posts / 0 new
Author
Message
#1
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

When you have a global struct you want to make volatile cause it's shared between main() and an ISR(), do you have to put the "volatile" keyword in front of every member variable? Or in the struct definition? Or just when declaring the struct?

i.e. Can you just write:

typedef struct
{
  char var1;
  float var2;
} struct1;

volatile struct1 MyStruct;

Or do you have to write this:

typedef struct
{
  volatile char var1;
  volatile float var2;
} struct1;

volatile struct1 Mystruct;

Or this...

typedef volatile struct
{
  volatile char var1;
  volatile float var2;
} struct1;

volatile struct1 Mystruct;

Also, if you have a variable used in 2 different ISRs but never in main(), will volatile still make sure it is not optimised out so that each ISR can see it? Or does this only work if the variable also appears in main() in which case you'd need to initialize it or something in main() to get this result. I'm asking this question because I had a problem with this very thing... a variable that only existed in two ISRs did not seem to get updated correctly even though it was made volatile until I added an unnecessary init to zero line in main().

Thanks,
James

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

The first one (have a read of the C standard and the description of 'volatile' it specifically says that it applies to the components of composite object and not the object itself.

As for two ISR's - yes the variables would need to be 'volatile' because the rule is to use it on variables in two or more paths of execution. That can be main+ISR or ISR1+ISR2

Basically the word just means "this variable may be changed from something outside the current path of execution"

  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

Thanks a lot Cliff!

Sincerely,
James