/* Experiment for creating c++ objects dynamically and deleting them What: How can c++ memory leaks be avoided whe using dynamic objects? why: Memory leaks have to be avoided for long time operation. I memory need over time increases, the system will crash. how: create and delete objects by commands from the serial line ( see help command in the code ) Original example with static functions "Blink without delay" from adafruit https://learn.adafruit.com/multi-tasking-the-arduino-part-1/a-classy-solution extended with for memory test by 2025-02-24 mchris */ uint8_t Idx = 0; 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; //Flasher* flasherPtr=this; Serial.print("object: "+String(Idx)+" "); Serial.print("address: "); Serial.println((int)this); } void exec() { // 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 } } }; #define LEDARRAYT_LEN 10 Flasher *Liste[LEDARRAYT_LEN]; void setup() { Serial.begin(115200); Idx = 0; Liste[Idx++] = new Flasher(12, 100, 400); Liste[Idx++] = new Flasher(13, 350, 350); } void loop() { // run the objects is no serial char availabe while (!Serial.available()) for (int n = 0; n < Idx; n++) Liste[n]->exec(); // check the commands char c = Serial.read(); if (c == 'd') { Serial.println("delete"); Idx = 0; for (int n = 0; n < Idx; n++) delete(Liste[n]); } if (c == 'n') { Serial.println("create new list"); Idx = 0; Liste[Idx++] = new Flasher(12, 100, 400); Liste[Idx++] = new Flasher(13, 350, 350); } if (c == 'h') { Serial.println("== help =="); Serial.println("d: delete"); Serial.println("n: new list"); } }