How to use main function to replace setup and loop?

I don't want to use setup and loop function to write the Arduino programs , I want to use main function in C to start .. The official site says that Arduino support C

int main()
{
    pinMode(8,OUTPUT);
    while(1)
    {
	  digitalWrite(8,HIGH);
	  delay(1000);
	  digitalWrite(8,LOW);
	  delay(1000);
    }
}

My pin 8 is link to a led module , but it only turn on the LED , the LED doesn't blink

But if I use the code below , it achieve my goal

void setup()
{
	pinMode(8,OUTPUT);
}
void loop()
{
	digitalWrite(8,HIGH);
	delay(1000);
	digitalWrite(8,LOW);
	delay(1000);
}

but I really don't want to use setup and loop ...Can anyone tell me how to use main function to start?
Thanks

I don't think either of those codes will work. Where are HIGH and LOW defined ?

Yes it works , HIGH and LOW are build in constant

The IDE provides main() which in turn calls setup() and loop(). So you can't with the IDE.

Mark

You're not calling "init()", so all sorts of things like timers aren't initialized.

I don't want to use setup and loop function to write the Arduino programs

Why? What difference does it make?

Because the scope of variable in setup and loop is weird ..... Anyway , Just use it ..

holmes4:
The IDE provides main() which in turn calls setup() and loop(). So you can't with the IDE.

Mark

The IDE provides main() only if one does not exist.

AWOL provided the reason why OPs code fails, which you also missed.

Darsondu:
Because the scope of variable in setup and loop is weird ..... Anyway , Just use it ..

No they aren't. Scoping rules for setup and loop follow the standard C/C++ rules.

If you want to use main you can do it this way.

Not tested extensilvely, it seems to work
two tricks

  1. #undef main // removes the existing main from the compilers memory
  2. call init(); as first step in main()
//    FILE: main.ino
//  AUTHOR: Rob Tillaart
// VERSION: 0.1.00
// PURPOSE: demo
//    DATE: 2014-01-12
// Released to the public domain

#undef main

int main()
{
  init();
  
  pinMode(8, OUTPUT);
  Serial.begin(115200);
  
  while(1)
  {
    digitalWrite(8, HIGH);
    delay(1000);
    digitalWrite(8, LOW);
    delay(1000);
    Serial.println("Hello");
  }
  return 0;
}

please confirm it works

1 Like

Darsondu:
Because the scope of variable in setup and loop is weird ..... Anyway , Just use it ..

No it isn't. main is a function, setup and loop are functions. There is absolutely no difference.

But if I use the code below , it achieve my goal

Code:

void setup()

{
pinMode(8,OUTPUT);
}
void loop()
{
digitalWrite(8,HIGH);
delay(1000);
digitalWrite(8,LOW);
delay(1000);
}




but I really don't want to use setup and loop ...Can anyone tell me how to use main function to start?

Write it like this, then:

void setup()
{
    pinMode(8,OUTPUT);
    while(1)
    {
	  digitalWrite(8,HIGH);
	  delay(1000);
	  digitalWrite(8,LOW);
	  delay(1000);
    }
}
void loop() { }

What's the difference?