//simple example for how to use object oriented programming in arduino
#define LED_PIN 13 // define the pin, the led is connected to
class Led { // add new class
private: // only accessable within the class
byte _pin; //attribut for class "Led", the pin a LED is connected to
bool _ledState = LOW;
unsigned int _previousMillis = 0;
unsigned int _myTime;
public: // accessable outside of the class
Led(){} //default constructor, so do not use
Led(byte pin){ //define a constructor
_pin = pin; //set the pin of the led to the pin number, the constructor is called with
}
void init(){ // set the pinmode of the pin, the constructor is called with
pinMode(_pin, OUTPUT);
}
void init(byte defaultState){ // define a methode to set the LED in some default State
init(); // call the first init() function to set the pinmode
if (defaultState == HIGH){ on();} // set default state by calling the on()/off() function
else{off();}
}
void on(){ // turn on the pin the constructor is called with
digitalWrite(_pin, HIGH);
}
void off(){ //turn off the pin, the constructor is called with
digitalWrite(_pin, LOW);
}
void blink(int ON_TIME, int OFF_TIME){
unsigned int currentMillis = millis();
if ((currentMillis - _previousMillis >= OFF_TIME) && (_ledState == LOW)) {
_previousMillis = currentMillis;
_ledState = HIGH;
digitalWrite(_pin, HIGH);
}
if((currentMillis - _previousMillis >= ON_TIME) && (_ledState == HIGH)){
_previousMillis = currentMillis;
digitalWrite(_pin, LOW);
_ledState = LOW;
}
}
};
Led led13(LED_PIN); //create a new object by calling the constructor of the class Led, now pin = 13,
void setup() {
Serial.begin(9600);
led13.init(HIGH); // initialize a default high state
delay(500);
Serial.println("LED 13 is initialized");
delay(2000);
}
void loop() {
led13.blink(500,2000);
}