1

Today i had my 10th, or 12th hour of Arduino in University, we were assigned a paper with only 2 parts, the questions and a picture of a TinkerCAD circuit, we had to wire this circuit, then wrote a code to light up the LED TinkerCAD Circuit

i know void setup(){} runs only once, and that void loop(){} loops forever, i wrote the following code to light up the led

 void setup(){
  pinMode(7,OUTPUT);
  digitalWrite(7,HIGH);
}

but Arduino expected a void loop()at the end, even if its empty, why is that?, why cant it run without it since an empty loop is essentially the same as no loop?, what is the reason the compiler cant ignore the lack of a void loop?

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190

1 Answers1

0

What you see in your Arduino sketch is not everything that will be executed in the Arduino board.

Instead they provide you with some friendly functions, so it's easier for makers to easily produce code for the Atmega microcontrollers present in the Arduinos.

You can imagine that there's the following pseudo-program executing in the background of what you see

setup();

while (true) {
    loop();
}

So this program requires you to have a function called setup and a function called loop.

The setup will be called once at the beginning, and the loop will be called again and again in an infinite loop

Leaving loop empty if you don't need it to do anything is perfectly fine, but it's mandatory that you define such function.

  • Thank you very much! Is there a reason as to why Arduino doesnt check for validity of the loop? Kind of like this pseudocode: ` while (true) { loop(); if loop==null then false} ` BTW sorry for the bad formatting, couldnt get mini markdown to work the code – Sebastian Domínguez Oct 21 '22 at 16:05
  • because the continuous execution of loop is not subject to any condition. If there would be a condition what do you do? You never want loop to stop executing, otherwise the Arduino would hang and you would need to manually restart it. If you want to do something just once and not repeating it, put your code inside setup and leave loop empty –  Oct 21 '22 at 16:07
  • it can simply generate empty functions for you. this is not really a reason. – apple apple Oct 21 '22 at 16:14
  • @appleapple what it? the linker can't find the implementation of function `loop()`. it is called from `main`. `main' is in `core` (something like a SDK) (and they didn't add an empty implementation of loop() as `weak`) – Juraj Oct 21 '22 at 17:42