battle programmers alliance
Would you like to react to this message? Create an account in a few clicks or log in to continue.

battle programmers allianceLog in

the LivinGrimoire Artificial General Intelligence software design pattern forum

descriptionArduino OOP (object oriented programming) EmptyArduino OOP (object oriented programming)

more_horiz
Arduino OOP (object oriented programming) Arduino-Cheat-Sheet

Last edited by Moti Barski on Sun Apr 30, 2023 5:20 am; edited 2 times in total

descriptionArduino OOP (object oriented programming) EmptyRe: Arduino OOP (object oriented programming)

more_horiz
creating a header file: defining guards to ensure a class will be written only once in total ,
when it is imported on other files, regardless of how many other files use it:

Code:

#ifndef LED_H
#define LED_H

#endif

add a tab and name it Led.h:

Code:


class code skeleton:
#ifndef LED_H
#define LED_H
class Led{
    private:
          
    public:
};
#endif


Code:

#ifndef LED_H
#define LED_H
// using Arduino hardware codes outside main:
#include <Arduino.h>
class Led{
    private:
          byte pin;
      public:
  Led(){this->pin = 13;}
  Led(byte pin){
      this->pin = pin;
  }
  void init(){
      pinMode(pin, OUTPUT);
  }
  void on(){
      digitalWrite(pin, HIGH);
  }
  void off(){
      digitalWrite(pin, LOW);
  }
};
#endif


note!
// using Arduino hardware codes outside main:
#include <Arduino.h>
while #include <Arduino.h> is not needed in the main file it is needed on external .h files

main file with imported external C++ file containing the example Led class:

Code:

#define LED_PIN 13
// import the C++ file with the example Led class:
#include "Led.h"

Led led1(LED_PIN);
void setup()
{
  led1.init();
}

void loop()
{
  // turn the LED on (HIGH is the voltage level)
  led1.on();
  delay(1000); // Wait for 1000 millisecond(s)
  // turn the LED off by making the voltage LOW
  led1.off();
  delay(1000); // Wait for 1000 millisecond(s)
}


Last edited by Moti Barski on Fri Aug 18, 2023 8:02 am; edited 1 time in total

descriptionArduino OOP (object oriented programming) EmptyRe: Arduino OOP (object oriented programming)

more_horiz
Arduino OOP (object oriented programming) Add_cp10

Arduino OOP (object oriented programming) 4th_im10

Arduino OOP (object oriented programming) Add_cp11

descriptionArduino OOP (object oriented programming) EmptyRe: Arduino OOP (object oriented programming)

more_horiz
Arduino OOP (object oriented programming) 4th_im11

Arduino OOP (object oriented programming) Arduin11

descriptionArduino OOP (object oriented programming) EmptyRe: Arduino OOP (object oriented programming)

more_horiz
separate class implementation from it's interface,
(code will work also if you don't separate into an interface and a C++ file):

Led.h is an interface.
add a Led.cpp file/tab for the implementation:

updated code for 'Led.h' (the file was an entire class, but now just an interface code):

Code:

#ifndef LED_H
#define LED_H

#include <Arduino.h>

class Led
{
private:
  byte pin;
public:
  Led() {} // do not use
  Led(byte pin);

  // init the pin for the LED
  // call this in setup()
  void init();
  void init(byte defaultState);

  // power on the LED
  void on();
  // power off the LED
  void off();
};

#endif


Led.cpp file (the implementation):

Code:

#include "Led.h"

Led::Led(byte pin)
{
  this->pin = pin;
}

void Led::init()
{
  pinMode(pin, OUTPUT);
}

void Led::init(byte defaultState)
{
  init();
  if (defaultState == HIGH) {
    on();
  }
  else {
    off();
  }
}

void Led::on()
{
  digitalWrite(pin, HIGH);
}

void Led::off()
{
  digitalWrite(pin, LOW);
}


adding a class to a sketch:
1 (Arduino IDE)sketch->show sketch folder
2 paste the .h and .cpp files (or just .h file if it contains implementation code)
3 restart Arduino IDE
4 in the main file code add:
#include "className.h"

transform Arduino C++ classes into a library:

this requires moving the .h and .cpp files to a new directory in the Arduino library directory
and importing using a code line:

1 (Arduino IDE)sketch->show sketch folder->cut the .h and .cpp files->go 1 dir up
to the Arduino folder->library dir
2 create a new folder, and name it (Led for example)->paste the .h and cpp files into the new
dir(Led folder)
3 restart the Arduino IDE
4 in the begining of the main code, add the library(Led in this example):
#include <Led.h>

spellcaster

descriptionArduino OOP (object oriented programming) EmptyRe: Arduino OOP (object oriented programming)

more_horiz
push button class:

Code:

class PushButton
{
private:
  byte pin;
  byte state;
  bool isPullUp;
  bool internalPullUpActivated;
  unsigned long lastTimeStateChanged;
  unsigned long debounceDelay;
  bool btnWasReleased = true;
public:
  PushButton() {} // do not use
  PushButton(byte pin, bool isPullUp, bool internalPullUpActivated)
        {
  this->pin = pin;
  this->isPullUp = isPullUp;
  this->internalPullUpActivated = internalPullUpActivated;

  lastTimeStateChanged = millis();
  debounceDelay = 50;
      }

  void init(){
  if (isPullUp && internalPullUpActivated) {
    // use built in pull up resistor
    // and its state is read via the pushBtn 2nd connector
    pinMode(pin, INPUT_PULLUP);
  }
  else {
    // btn is connected to an actual resistor
    // and its state is read via the pushBtn 3rd connector
    pinMode(pin, INPUT);
  }
  state = digitalRead(pin);
}
  void readState()
{
  unsigned long timeNow = millis();
  if (timeNow - lastTimeStateChanged > debounceDelay) {
    byte newState = digitalRead(pin);
    if (newState != state) {
      state = newState;
      lastTimeStateChanged = timeNow;
    }
  }
}
  bool isPressed(){
  readState();
  if (isPullUp) {
   
    return (state == LOW);
  }
  else {
   
    return (state == HIGH);
  }
  }
  bool isEngaged()/*returns true once per press*/{
     bool temp = isPressed();
    bool temp2 = btnWasReleased;
    btnWasReleased = not temp;
    return temp && temp2;
  }
};
// global variables
#define BUTTON_PIN 2

PushButton button(BUTTON_PIN, true, true);
void setup() {
  Serial.begin(9600);
  button.init();
}

void loop() {
  if (button.isEngaged()) {
    Serial.println("Button is pressed");
  }
  else {
    Serial.println("Button is not pressed");
  }
  delay(100);
}


:s33:

descriptionArduino OOP (object oriented programming) EmptyRe: Arduino OOP (object oriented programming)

more_horiz
.h (interface file notes):
LedBlinker() {} // the default c'tor, no need to use in this case
the default constructor needs to be added to avoid compile error
on classes that utilize other classes. the blinker class uses the Led class.
but adding a default c'tor is a good coding practice on Arduino C++.

LedBlinker(Led &led); // & is added for byref params while by val params have no & added

.cpp file notes:

note the millis() functions is used to run code per time interval
instead of using the delay function, which jams the whole program from running.

this technique also enables running multiple tasks without holting one another.

LedBlinker dot h file interface

Code:

#ifndef LED_BLINKER_H
#define LED_BLINKER_H

#include <Arduino.h>
#include "Led.h"

class LedBlinker
{
private:
  Led led;
  unsigned long lastTimeBlinked;
  unsigned long blinkDelay;

  void toggleLed();

public:
  LedBlinker() {} // the default c'tor, no need to use in this case
  LedBlinker(Led &led); // & is added for byref params instead of by val
  LedBlinker(Led &led, unsigned long blinkDelay);

  void initLed();

  void update();

  unsigned long getBlinkDelay();
  void setBlinkDelay(unsigned long blinkDelay);
};

#endif


ledblinker.cpp

Code:

#include "LedBlinker.h"

LedBlinker::LedBlinker(Led &led)
{
  this->led = led;
  lastTimeBlinked = millis();
  blinkDelay = 500;
}

LedBlinker::LedBlinker(Led &led, unsigned long blinkDelay)
{
  this->led = led;
  lastTimeBlinked = millis();
  this->blinkDelay = blinkDelay;
}

void LedBlinker::initLed()
{
  led.init();
}

void LedBlinker::toggleLed()
{
  led.toggle();
}

void LedBlinker::update()
{
  unsigned long timeNow = millis();
  // use millis instead of delay to run a command per time interval:
  if (timeNow - lastTimeBlinked > blinkDelay) {
    lastTimeBlinked = timeNow;
    toggleLed();
  }
}

unsigned long LedBlinker::getBlinkDelay()
{
  return blinkDelay;
}

void LedBlinker::setBlinkDelay(unsigned long blinkDelay)
{
  this->blinkDelay = blinkDelay;
}

descriptionArduino OOP (object oriented programming) EmptyC++ enum

more_horiz
C++ enum

Code:

enum blinkStates {
  BLINK_DIS, // blink disable
  BLINK_EN, // blink enable
  LED_ON, // we want the led to be on for interval
  LED_OFF // we want the led to be off for interval
};
Serial.begin(9600);
enum blinkStates ledState;
ledState = LED_OFF;
Serial.println(ledState); // 3

descriptionArduino OOP (object oriented programming) EmptyRe: Arduino OOP (object oriented programming)

more_horiz

Code:

class A {
    public:
    void f() { Serial.println("A"); }
     void f2() { Serial.println("C"); }
};

class B : public A {
    public:
    void f() { Serial.println("B"); }
};


void setup() {
    A obj;    // base-class pointer

    Serial.begin(115200);
   obj.f(); //A
     B obj2;
     obj2.f2(); //C
     obj2.f(); //B
}

void loop() {
  delay(100);
}

joker
privacy_tip Permissions in this forum:
You cannot reply to topics in this forum
power_settings_newLogin to reply