Ehsan Zakeri
Ehsan Zakeri

Reputation: 39

volatile variables or volatile structure problems in C

Here is my header file (Header.h)

#include <stdio.h>
#include <string.h>
void Process(void);

and "Header.C"

#include <stdio.h>
#include <string.h>
#include "Header.h"

struct St{
    unsigned long int volatile Var1;
    unsigned long int volatile Var2;
    unsigned char volatile Flag;
};

extern struct ST Variable;

void Process(void){
Variable.Var1=Variable.Var2;
}

and Main file:

#include <stdio.h>
#include <string.h>
#include "Header.h"

struct St{
    unsigned long int volatile Var1;
    unsigned long int volatile Var2;
    unsigned char volatile Flag;
};

struct ST Variable;

//Interrupt each 10us

void TIM_IRQHandler(){

//Do something

    if(something==True)
    {
    Variable.Flag=1;
    Variable.Var2=AVariable; //AVariable is between 30-40
    }

}

int main(){

    while(1)
    {
    //wait 10ms
    if(Variable.Flag==1)
        {
        Process();
        Variable.Flag=0;
        }

    }

}

As you can see an Interrupt occurs each 10us and if it does some codes correctly it will change Var2 with a value between 30-40 and set a Flag variable. in Main code if Flag has been set it should be call process function and change Var1 with Var2 value. But sometimes I receive var1 with other strange values that they are not correct.I have tested my interrupt and I find out I never fill my Var2 with strange values.

void TIM_IRQHandler(){

//Do something


    if(something==True)
    {
    Variable.Flag=1;
    Variable.Var2= < 30-40>;
    }
   if(Variable.Var2>40 || Variable.Var2<30){
      printf("ERROR");
     } 

}

and all Interrupt function works fine but in Process function it makes me angry.

I will appreciate for any tricks that I didn't pay attention.

Upvotes: 0

Views: 958

Answers (1)

Yunnosch
Yunnosch

Reputation: 26703

Never expect anything when using the keyword "volatile" inside any kind of typedef. You are declaring the type "struct St", including the keyword. Your description implies that you expect a volatile behaviour on the variable "Variable", which is defined and declared without the keyword. In my experience the keyword only sometimes (depending on platform and compiler) has an effect inside a type. It seems to reliably have an effect if used in both, the definition and the declaration of a variable.

Try changing

struct ST Variable;

to

volatile struct ST Variable;

and

extern struct ST Variable;

to

extern volatile struct ST Variable;

Also, is there a typo around "St" != "ST", with a "struct ST" type being declared elsewhere?
Also, as a side note, you might want to move your type declarations into the header.

I currently do not have access to a C environment, so please excuse me not testing my answer.

Upvotes: 1

Related Questions