Nils Bergmann Nils Bergmann - 3 months ago 13
C++ Question

Variable in class is resetting by itselfs

I am working on an LED Fader for the arduino. For this i wrote a class which defines everything. But since yesterday i have a problem and can't solve it.
So far here is my code:

class LED {
int pins[4];
int r = 0;
int g = 0;
int b = 0;
int task = 1;
int taskgoal = 255;
public:
void newTask() {
...
}
void newGoal() {
...
}
boolean taskFinished() {
...
}
void runTask() {
if (taskFinished()) {
newTask();
newGoal();
cout << "New Task and new Goal.\n";
}
int current;
switch (task) {
...
}
if (current < taskgoal) {
switch (task) {
case 1:
cout << r << "+1" << "\n";
this->redefine(this->r + 1, this->g, this->b);
cout << r << "+1" << "\n";
break;
case 2:
cout << g << "+1" << "\n";
this->redefine(this->g, this->g + 1, this->b);
break;
case 3:
cout << b << "+1" << "\n";
this->redefine(this->r, this->g, this->b + 1);
break;
}
} else if (current > taskgoal) {
...
}
analogWrite(pins[0], this->r);
analogWrite(pins[1], this->g);
analogWrite(pins[2], this->b);
return;
}
void ledinit(int p[]) {
this->r = random(1, 255);
this->g = random(1, 255);
this->b = random(1, 255);
for (int i = 1; i < 3; i++) {
pins[i] = p[i];
pinMode(pins[i], OUTPUT);
}
pins[3] = p[3];
analogWrite(pins[0], this->r);
analogWrite(pins[1], this->g);
analogWrite(pins[2], this->b);
analogWrite(pins[3], LOW);
newTask();
newGoal();
runTask();
return;
}
void redefine(int rr, int gg, int bb) {
r = rr;
g = gg;
b = bb;
return;
}
};
std::vector< LED >leds;

void setup() {
Serial.begin(9600);
LED l1;
int l1pins[4] = {11, 9, 8, 10};
l1.ledinit(l1pins);
leds.push_back(l1);
}

void loop() {
for (LED l : leds) {
l.runTask();
cout << "Run Task" << "\n";
}
delay(100);
}


(Pastebin: http://pastebin.com/pQMEkG1a)
In Line 76 i try to add 1 to the r value with my function redefine. I also tried it directly with this->r++; or this->r += 1; but all has the same result. It will add the 1 to the r variable. But at the next Loop it is again the same value like at the beginning. This is how the output looks like:

Run Task
45+1
46+1
Run Task
45+1
46+1
Run Task
45+1
46+1


But why it is everytime 45. I think it is a very easy fault by me but i can't find it.

Nils

Answer

Looking at the code, I would expect that your problem lies within for (LED l : leds)

This range-based for loops over a vector of LEDs, takes from each element a copy, on which you will run the task.

I would suggest writing the following: for (LED &l : leds) to prevent the copy.

As it looks like your compiler supports C++11, you might want to prevent similar issues in the future by adding following member function to the class LED: LED(const LED &) = delete; and possibly a few others from the rule of five. This will prevent any copy from the led. Possibly you will require some move-constructor in order to add the LEDs in the vector.

Comments