init() function

I've gone on a hunt a few times now and can't find where the init() function lives in my Arduino folder or better what code it contains. I want to inspect its contents so I can pick and choose what code I include in projects. Rather than using setup() and loop(), one can use int main(void) instead and place an endless for loop

int main(void) {
  init();  // needed for things like clocks, timers and uart
  // setup() code here
  for(;;) {
    // loop() code here
  }
}

Can anyone direct me to the filepath of this code or the code itself?

hardware/arduino/cores/arduino/wiring.c

1 Like

Hello :slight_smile:

This is all the code inside hardware\arduino\cores\arduino\main.cpp :

#include <Arduino.h>

int main(void)
{
	init();

#if defined(USBCON)
	USBDevice.attach();
#endif
	
	setup();
    
	for (;;) {
		loop();
		if (serialEventRun) serialEventRun();
	}
        
	return 0;
}

Thank you both! Once I was able to inspect the contents of init() I quickly figured out which bits I needed to get PWM working on pin 11. For anyone else that finds this thread later, here is the secret sauce (assuming like me you don't want to call init() and incur the penalty in sketch size.

sbi(TCCR2A, COM2A1);
sbi(TCCR2B, CS22);
sbi(TCCR2A, WGM20);

My sketch which blinks an led on pin 11 with analogWrites (PWM) now fits in 210 bytes where it used to consume 1,380 bytes! I know it is a trivial example but I enjoy learning the low level stuff rather than including the default routines which often carry performance and size penalties.

#include <util/delay.h>

#define bitmask _BV(PB3)
#define mask _BV(PB5) | bitmask    // Also mask off Digital PIN 13 so the onboard LED is off
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))

int main(void) {
  DDRB = mask;  // Disable the onboard LED as well as allow pin 11 to blink
  sbi(TCCR2A, COM2A1);
  sbi(TCCR2B, CS22);
  sbi(TCCR2A, WGM20);

  for(;;) {    
    OCR2A = 1;  // set pwm duty
    _delay_ms(50);
    OCR2A = 0;  // set pwm duty to zero
    _delay_ms(1000);
  }
}
1 Like