I currently know 3 ways to do a program. Which one of them is the most memory friendly. Note that the example code is simple (blinking a led) and the final code will be VERY VERY complex. Also, the way I code is not the best, so suggest any suggestions in the way to write things or where to put them please.
1- All in the loop. The most basic way of programming.
const int led = 2;
const int interval = 500;
bool ledState = false;
void setup() {
pinMode(led, OUTPUT);
}
void loop() {
ledState = !ledState;
digitalWrite(led, ledState);
delay(interval);
}
2- Functions. Similar to the loop but a little neither. Can be splitted into many tabs.
const int led = 2;
const int interval = 500;
bool ledState = false;
void setup() {
pinMode(led, OUTPUT);
}
void loop() {
blinkLed();
}
void blinkLed()
{
ledState = !ledState;
digitalWrite(led, ledState);
delay(interval);
}
Then finnaly, objects. The most supreme of them all (and the one that I know the least). I like objects and classes because multitasking with it is much easier. It is more flexible too. Code taken from here.
class Flasher
{
// Class Member Variables
// These are initialized at startup
int ledPin; // the number of the LED pin
long OnTime; // milliseconds of on-time
long OffTime; // milliseconds of off-time
// These maintain the current state
int ledState; // ledState used to set the LED
unsigned long previousMillis; // will store last time LED was updated
// Constructor - creates a Flasher
// and initializes the member variables and state
public:
Flasher(int pin, long on, long off)
{
ledPin = pin;
pinMode(ledPin, OUTPUT);
OnTime = on;
OffTime = off;
ledState = LOW;
previousMillis = 0;
}
void Update()
{
// check to see if it's time to change the state of the LED
unsigned long currentMillis = millis();
if((ledState == HIGH) && (currentMillis - previousMillis >= OnTime))
{
ledState = LOW; // Turn it off
previousMillis = currentMillis; // Remember the time
digitalWrite(ledPin, ledState); // Update the actual LED
}
else if ((ledState == LOW) && (currentMillis - previousMillis >= OffTime))
{
ledState = HIGH; // turn it on
previousMillis = currentMillis; // Remember the time
digitalWrite(ledPin, ledState); // Update the actual LED
}
}
};
Flasher led(2, 500, 500);
void setup()
{
}
void loop()
{
led.Update();
}
So, which is the best out of those 3.