Search code examples
arduinoarduino-esp8266

How do I periodically append to an array using the Arduino IDE?


I am trying to append float values that the user inputs through the serial monitor. I need these values stored in an array in a sequential fashion, i.e. each time I get a value, I must append it to the array.


Solution

  • Arduino doesn't come out of the box with dynamic data structures (except for String).

    You can download open source implementations of generic containers from the web. Here's one: https://github.com/dhbikoff/Generic-C-Library/blob/master/vector.h

    Also, here's a simple linked-list/vector I implemented myself as a toy project.

    Be careful with dynamic memory. Memory fragmentation can cause your sketch to crash randomly (has happened to me several times).

    template <typename T>
    struct SimpleVector {
        struct SimpleVectorNode {
            T* m_value = NULL;
            SimpleVectorNode* m_next = NULL;
    
            SimpleVectorNode() {
    
            }
    
            SimpleVectorNode(T val) {
                m_value = new T(val);
                m_next = NULL;
            }
        };
        int m_size = 0;
        SimpleVectorNode* m_head = new SimpleVectorNode;
    
        void AddValue(T val) {
            ++m_size;
            SimpleVectorNode* end = m_head;
            while (end->m_next != NULL) {
                end = end->m_next;
            }
            end->m_next = new SimpleVectorNode(val);
        }
    
        SimpleVectorNode* Seek(int index) {
            SimpleVectorNode* res = m_head;
            while (index >= 0) {
                --index;
                res = res->m_next;
            }
            return res;
        }
    
        T& Get(int index) {
            return *(Seek(index)->m_value);
        }
    
        void Delete(int index) {
            SimpleVectorNode* preDel = Seek(index - 1);
            SimpleVectorNode* toDel = preDel->m_next;
            preDel->m_next = toDel->m_next;
            delete toDel->m_value;
            delete toDel;
            --m_size;
        }
    
        int GetSize() {
            return m_size;
        }
    
        int IndexOf(T val) {
            SimpleVectorNode* pNode = m_head->m_next;
            for (int i = 0; i < m_size; ++i) {
                if (pNode->m_value == val) {
                    return i;
                }
    
                pNode = pNode->m_next;
            }
    
            return -1;
        }
    
        bool Contains(T val) {
            return IndexOf(val) >= 0;
        }
    
        ~SimpleVector() {
            while (m_size > 0) {
                Delete(0);
            }
    
            delete m_head;
        }
    };