Volatile struct

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

Does declaring volatiles in structures work?
I have the following declaration in my header file

struct twi_struct{
	volatile unsigned char flag;
	volatile unsigned char state;
	volatile unsigned char device;
	volatile unsigned char data[TWI_BUFFSIZE];
	volatile unsigned long timer;	
};

extern struct twi_struct twi;

And this is in .c file

struct twi_struct twi;

I have a function that uses a pointer to fill twi.data[] The filling is actually carried out in an interrupt routine.
If I fill the array twi.data with 0, start the interrupt, wait for the twi comms to take place, and then try and read twi.data[i] within the same function, I always get 0;
If I split the interrupt part out to a separate function, reading twi.data returns the values put into it by the interrupt routine.

Is there something about my structure declaration that is removing the volatile attribute from the variables?

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

the shared data between the ISR and the main function must be defined volatile

try it and tell us the results !!

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

There is a difference between a volatile struct and a struct with volatile members. I can't remember all the details but googling volatile struct would probable get you the necessary info. Maybe declaring the struct volatile would help. Also, without seeing any of your code it's hard to guess what the problem might be.

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

Try:

volatile struct twi_struct twi;
  • 1
  • 2
  • 3
  • 4
  • 5
Total votes: 0

atomicdog wrote:
There is a difference between a volatile struct and a struct with volatile members. I can't remember all the details but googling volatile struct would probable get you the necessary info. Maybe declaring the struct volatile would help. Also, without seeing any of your code it's hard to guess what the problem might be.

i am not also sure about this point. but it seems from the simple think that the 2 lead to each other .. i mean what is the difference if you defined :

 
struct 
{
      volatile short Header;
      volatile short Tail;
      volatile unsigned chat Payload[100]; 
} Packet;

or ..

volatile struct 
{
      short Header;
      short Tail;
      unsigned chat Payload[100]; 
} Packet;

Regards,
-- A.El-Saeed

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

Erm,
Thanks for all the feedback.

As it turns out the volatile bit works fine. After sleep and some more messing around I realised that the test for valid data in the buffer wasn't working, so it was trying to read the data before the buffer was filled.
Some how it's always the easiest bit that catches me out, because I don't even think to check it.