Pages: [1]   Go Down
Author Topic: init() function  (Read 760 times)
0 Members and 1 Guest are viewing this topic.
Offline Offline
Newbie
*
Karma: 0
Posts: 33
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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

Code:
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?
Logged

UK
Offline Offline
Faraday Member
**
Karma: 99
Posts: 4153
Where is your SSCCE?!?!
View Profile
WWW
 Bigger Bigger  Smaller Smaller  Reset Reset

hardware/arduino/cores/arduino/wiring.c
Logged

Get 10% off all 4D Systems TFT screens this month: use discount code MAJENKO10

France
Offline Offline
God Member
*****
Karma: 34
Posts: 987
Scientia potentia est.
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Hello smiley

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

Code:
#include <Arduino.h>

int main(void)
{
init();

#if defined(USBCON)
USBDevice.attach();
#endif

setup();
   
for (;;) {
loop();
if (serialEventRun) serialEventRun();
}
       
return 0;
}
Logged

Offline Offline
Newbie
*
Karma: 0
Posts: 33
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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.

Code:
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.

Code:
#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);
  }
}





Logged

Pages: [1]   Go Up
Jump to: