2

I tried to compile the following code (using Arduino 1.8.16 with an esp8266-12)

extern volatile unsigned long timer0_millis;
unsigned long new_value = 0;

void setup(){
  //Setup stuff
}

void loop(){
  //Do stuff
  //--------

  //Change Millis
  setMillis(new_value);
}

void setMillis(unsigned long new_millis){
  uint8_t oldSREG = SREG;
  cli();
  timer0_millis = new_millis;
  SREG = oldSREG;
}

from an answer to this question, but I get the following error

 error: 'SREG' was not declared in this scope
   uint8_t oldSREG = SREG;
                 ^
exit status 1
'SREG' was not declared in this scope

I wouldn't necessarily want to use this code for any real purpose, other than as an exercise in learning. What am I missing? What is SREG ?

1 Answer 1

1

SREG is the processor status register. One of the bits in there is the interrupt flag, which is cleared with the cli() command and reset at the end of the function. Why the original poster used the register instead of just using cli/sei is unclear. (Note: Instead of cli() and sei() the arduino documentation uses the much clearer equivalents noInterrupts() and interrupts().)

This SREG register is, in this form, hardware specific and therefore not available if you're using the esp8266 toolchain. The above code builds fine with an Arduino Uno or similar board. To build for the esp8266, change the code to:

void setMillis(unsigned long new_millis){
  noInterrupts();
  timer0_millis = new_millis;
  interrupts();
}

I don't have such a board, so I can't verify it really works on this board. You might get a linker error about a non-existing timer0_millis variable.

2
  • 1
    Re “Why the original poster used the register instead of just using cli/sei is unclear”: If setMillis() is ever called from a critical section (a context where interrupts are turned off), you don't want it to enable interrupts before returning. Oct 19, 2021 at 7:18
  • Ok, that makes sense, but is a bit beyond the point he's trying to make there, I think.
    – PMF
    Oct 19, 2021 at 7:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.