Is there a risk of interrupts in setup?

I found the below setup function from some forum code while trying to understand Timer1.

I was curious as to why the author use the "interrupts()" & "noInterrupts()" in the setup function.
I would have thought interrupts were disabled on bootup.

Am I wrong?


void setup()
{
  Serial.begin(9600);
  while (!Serial);
  Serial.println(" Starting ....");
  
  pinMode(TriggerPin, OUTPUT);
  pinMode(EchoPin, INPUT);
  pinMode(LedPin, OUTPUT);

  digitalWrite(TriggerPin, LOW);
  digitalWrite(LedPin, LOW);

  noInterrupts ();  // protected code
  // reset Timer 1
  TCCR1A = 0;
  TCCR1B = 0;
  TCNT1  = 0;
  TIMSK1 = 0;

  TIFR1 = _BV(ICF1); // clear Input Capture Flag
  TCCR1B = TCCR1BCaptureRisingEdge;
  interrupts ();
}



They are disabled on boot, but are enabled somewhat before setup() is called, in init()

After all, it's not uncommon for setup() to use delay() or write to a serial port, both of which require that interrupts be running.

main(), which sketch execution nominally starts, looks like:

int main(void)
{
	init();
	initVariant();
	setup();
    for (;;) {
		loop();
		if (serialEventRun) serialEventRun();
	}
}
2 Likes

Regardless of where it's done, if you're tinkering with the settings of timers and other hardware devices, it is sometimes wise, even necessary, to disable interrupts just to ensure things get initialized properly, and interrupts do not occur until you are prepared to handle them.

1 Like

Thank you. It's been along time since I used C without the "help" of the Arduino IDE macro's. When I first started with the Arduino (from Microchip) I stubbornly forced myself to do it the "old" way. Then when I was rushing to see how a sensor worked I slipped down the slope and become defendant on the IDE Macro's. Kinka like opioids :slight_smile:

Oh and I'm not a programmer I'm mostly a hardware engineer. I'm sure that explains a lot :slight_smile:

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.