This discussion has been locked.
You can no longer post new replies to this discussion. If you have a question you can start a new discussion

volatile keyword

The application note suggests to wrap a timer tick variable in a function which disables all interrupts, reads and copies the variable into a temp, re-enables interrupts, then returns the temp.

Can the variable be accessed directly outside of the ISR without disabling interrupts if the timer tick variable is declared as "volatile?"

Parents
  • This has nothing to do with volatile, it has to do with the '51 being an 8 bit device.

    Example:
    a counter is incremented in the ISR and read in main. The count now is 0x1ff

    Main read low byte to a register = 0xff
    INTERRUPT HAPPEN HERE
    ISR increment counter to 0x200
    interrupt exit
    main read high byte 0x02
    

    As you see, in this scenario main would read 0x2ff instead of 0x200. Reversing the read of high and low bytes changes, but does not cure, the problem.

    Erik

Reply
  • This has nothing to do with volatile, it has to do with the '51 being an 8 bit device.

    Example:
    a counter is incremented in the ISR and read in main. The count now is 0x1ff

    Main read low byte to a register = 0xff
    INTERRUPT HAPPEN HERE
    ISR increment counter to 0x200
    interrupt exit
    main read high byte 0x02
    

    As you see, in this scenario main would read 0x2ff instead of 0x200. Reversing the read of high and low bytes changes, but does not cure, the problem.

    Erik

Children
  • IMHO, "volatile" really _should_ play a role here.

    From the point-of-view of the C language definition, any object whose value may change for reasons not explicitly part of the C program itself (e.g. a counter/timer) should still work as expected, *if* it's declared "volatile". It's in the responsibility of the compiler to ensure that it does.

    For the sake of the 8051, this means that a large fraction of the SFRs should implicitly be considered volatile. If a variable larger than 1 byte is declared "volatile", the compiler would have to turn off interrupts while accessing it automatically. That's one of the effects of the "volatile" qualifier.

  • From K&R:

    "The purpose of volatile is to force an implementation to suppress optimisation that could otherwise occur"

    So there you are: its sole purpose is to control optimisation - not to guarantee atomic accesses, nor anything else.