-6

instead of making libraries, can we have two or more classes within arduiono IDE? if so then can i call the objects of those classes within that code in seperate functions? like for example i have a communications class say SPI and an another class lcd() which commands an arduino peripheral and sets its register values by using the SPI class objects. after that, staying within the same code, i create a function, say, void loop() which creates the lcd object and uses it. my question is can i create multiple classes like this or do i have to use seperate libraries because i want my stuff to be in one place and not scattered in seperate .cpp and .h files. thanks for your time :)

1 Answers1

0

Yes, it is possible to put the classes in the main file and use the classes. You must initialize the classes before using them in void loop(), else the class won't be recognised.

For example:

class serial
{
   public:
   serial(){Serial.begin(9600);}
   void printLine(String text){Serial.println(text);}
};

serial serialObject; //Must be a global variable to use in setup and loop function

void setup() {
serial serialObject;
}

void loop() {
serialObject.printLine("Hello");
}

Personally I think it is a better habit to put classes in separate .h and .cpp files for readability.

Joost Baars
  • 84
  • 10
  • well said @judioJ ive now understood what you mean. It would be very hectic to scroll around the same sketch i am now putting methods in cpp file and linking them with .h file by using :: operator . this is making things quite easy now . regards – ibad-ur-rahman Oct 24 '18 at 08:16