The picture above shows the simplest of Arduino programs, what you get when you select File -> New from the menu. There are two mandatory function calls:
setup- code that will be executed once when the program begins
loop- code that is continuously run in a loop, over & over
Neither function must do anything. There are sketches that do everything just once in
setup and some programs that don't use
setup at all and just use
loop. But both must be defined, even if they are empty like shown above.
CircuitPython does not put restrictions on having either code which is executed at the start like the Arduino
setup function or any sort of repetitive main code like the Arduino
That said, many CircuitPython programs are structured very similarly to how an Arduino sketch program is structured.
A simple example. A program that defines a variable
var to be the value
5 and then prints that value over and over, kinds similar to the old BASIC Hello World programs. In Arduino, you might write this as follows:
The program adds a bit of code to open the serial connection and print the output.
The equivalent CircuitPython program would be:
setup type statements are placed near the top of the program.
An infinite loop like the Arduino
loop function can be done in Python via a
while loop with the condition set to
True so that it never exits the
The serial monitor is "baked in" to CircuitPython, the user does not have to set anything up to use it and this will be discussed more in-depth in this guide.
There is no constraint that CircuitPython must do an infinite loop at all. A simple program might read a temperature sensor, print the output and end.
But, both Arduino and CircuitPython run on microcontrollers. In a class, you might want to do something like read and print a temperature value once. If this project were deployed to a farmer's field, it would probably read the temperature over and over, probably so many times a minute or hour. The code should never stop when out in the farmer's field.
So an infinite loop to do certain functions is of great utility and is used in a majority of microcontroller programs. This is why Arduino has simplified things for beginners, to show that you may want to have a
loop. You can do the exact same things in CircuitPython, you just structure your code to provide the same functionality.