You shouldn't block the loop
function in Arduino. If you look how main
is defined (<arduino_install_dir>\hardware\arduino\avr\cores\arduino\main.cpp
) you will see:
int main(void)
{
init();
initVariant();
#if defined(USBCON)
USBDevice.attach();
#endif
setup();
for (;;) {
loop();
if (serialEventRun) serialEventRun();
}
return 0;
}
If you block the first loop call with a while (true)
you don't get serialEventRun
a chance to be called. As far as I can tell it is used to handle serial events.
So yes, it is true that global variables should generally be avoided. However because of how Arduino sketch is designed for small programs I can say you should stick with the recommended Arduino style of global variables + setup
+ loop
.
What you can do to alleviate this is organize your code into classes that abstract your model. For instance if you control a motor instead of:
#define DRIVER_EN 5
#define DRIVER_DIR 6
#define DRIVER_PUL 7
int motor_microstepping;
int motor_gear_ratio;
void setup()
{
motor_microstepping = 8;
motor_gear_ratio = 2;
pinMode(DRIVER_EN, OUTPUT);
pinMode(DRIVER_DIR, OUTPUT);
pinMode(DRIVER_PUL, OUTPUT);
digitalWrite(DRIVER_EN, LOW);
}
I have created a class for my motor controller. This is how it is used:
using namespace em::physics::literals;
em::motor::TB6600 slider_motor{
5, // EN
6, // DIR
7, // PUL
1.8_deg, // pulse_angle
8, // microstepping
1, // gear ratio
};
void setup()
{
slider_motor.setup();
}
void loop()
{
// ...
slider_motor.enable();
slider_motor.set_direction_low();
//...
}