Hallo,
Ich brauche ein Objekt, das zur Laufzeit erstellt wird, welches andere
Objekte enthält, die zur Objekterstellung erstellt werden sollen. Das
ganze soll 1-x LEDs ansteuern.
Schlauerle in mir sagt: klar, zwei Klassen - eine LED() und eine
LEDController().
LEDController bekommt eine attach()-Methode in der LED-Objekte zu einer
Liste hinzugefügt werden.
So weit, so theoretisch. Nur dann steige ich mit den Pointern aus.
Bei einer "modernen" Sprache (bitte nicht hauen) würde ich in etwa
soetwas machen:
(VORSICHT! - PseudoCode)
public class LEDController
{
int ledCount;
LED LEDArray[10];
public LEDController()
{
ledCount = 0;
}
public void attach(int _pin)
{
LEDArray[ledCount] = new LED(_pin);
}
public LED getChannel(int _channel)
{
return LEDArray[_channel];
}
}
public class LED
{
int _pin;
public LED(int pin)
{
pinMode(pin, OUTPUT);
_pin = pin;
}
public void blink()
{
digitalWrite(_pin, HIGH);
delay(250);
digitalWrite(_pin, LOW);
delay(250);
}
}
LEDController c1 = new LEDController();
void setup()
{
c1.attach(D0);
c1.attach(D1);
c1.attach(D2);
}
void loop()
{
c1.getChannel(0).blink();
}
In der richtigen Welt hab ich folgendes probiert:
test.ino
#include "ledcontroller.h"
#include "led.h"
LEDController myLedController;
void setup()
{
myLedController.attach(LED(D1));
}
void loop()
{
myLedController.getChannel(0)->blink();
}
LEDController.h
#ifndef ledController_h
#define ledController_h
#include "Arduino.h"
#include "led.h"
class LEDController
{
public:
LEDController();
void attach(LED _led);
LED getChannel(int _channel);
private:
LED _ledArray[10]{};
int _ledcount;
};
#endif
LEDController.cpp
LEDController::LEDController()
{
_ledcount = 0;
}
void LEDController::attach(LED _led)
{
_ledArray[_ledcount] = _led;
_ledcount++;
}
LED LEDController::getChannel(int _channel)
{
return _ledArray[_channel];
}
LED.h
#ifndef led_h
#define led_h
#include "Arduino.h"
class LED
{
public:
LED(int pin);
LED();
void blink();
private:
int _pin;
};
#endif
LED.cpp
#include "Arduino.h"
#include "led.h"
LED::LED(int pin)
{
pinMode(pin, OUTPUT);
_pin = pin;
_state = 0;
}
void LED::blink()
{
digitalWrite(_pin, HIGH);
delay(250);
digitalWrite(_pin, LOW);
delay(250);
}
Aber - klar, funktioniert so nicht. Ich muss das irgendwie miteinander
verschwurbeln, krieg es aber nicht hin... Ich glaube zu wissen, dass die
Lösung Pointer hat - einfach nur, weil ich sogut wie keine habe