Question

Currently I'm using Arduino for my project and what I want is to have an array that stores an array of sensors. I do understand that there's limited resource to be used for a dynamic array. But by limiting the number of items in the array and uses struct data instead of creating a class, I managed to cut the SRAM cost. So without further ado, here's my code :

#define MAX_SENSOR 6

namespace Sensors
{
    typedef struct
    {
        byte SlavePin;
        byte LDRPin;
        byte RedPin;
        byte BluePin;
    } Sensor;

    Sensor _sensors[MAX_SENSOR];
    byte _len = 0;

    void Add(Sensor s)
    {
        if (_len > MAX_SENSOR)
            return;
        _len++;
        _sensors[_len] = s;
    }

    Sensor Get(byte index)
    {
        return _sensors[index];
    }
}

And here's how I use it.

#include "Sensors.h"

void setup()
{
    for (int i = 0; i < 6; i++)
    {
        Sensors::Sensor sen;
        sen.SlavePin = 0;
        Sensors::Add(sen);
    }
    Serial.print("Length = ");
    Serial.println(Sensors::_len);

    for (int j = 0; j < Sensors::_len; j++)
    {
        Serial.print(j);
        Serial.print(" = ");
        Serial.println(Sensors::Get(i).SlavePin);
    }
}

void loop() { //Nothing goes here }

This code works and it compiles successfully. But when I run it, the serial window shows this :

Length : 6

Sensor 0:0

Sensor 1:0

Sensor 2:1

Sensor 3:2

Sensor 4:3

Sensor 5:4

Apparently, the first and the second item in the array has the same value and honestly, I don't know why.

Here's the output that I'm expecting :

Length : 6

Sensor 0:0

Sensor 1:1

Sensor 2:2

Sensor 3:3

Sensor 4:4

Sensor 5:5

Any help would be very appreciated. And BTW, I'm sorry if this kind of thread had already existed.

Was it helpful?

Solution

The first call to Add() places the structure at index 1:

byte _len = 0;

void Add(Sensor s)
{
    if (_len > MAX_SENSOR)
        return;
    _len++;
    // On first call _len will be 1
    _sensors[_len] = s;
}

I understand the design intent of this code, but consider that this is a wasteful approach for a microcontroller.

Implementing Add() increases the code size. A library for a desktop computer would surely rate the code size a fair trade off for safety. A library for a microcontroller is harder to rate as good use of scarce memory.

Implementing Get() increases code size and execution time. Again, this seems like a good design for typical desktop environment and a library that you want to be safe. On a microcontroller, this is wrong.

The factor I see as key decider of good or bad is the permanent cost versus a one time savings. The safe version of Sensor costs code space and execution time on every system deployed and every second the program is running. The benefit is only the first day you are run and debug the program.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top