I'm trying to write an Arduino library to interface to a shield I designed, and I would like to imitate many of the libraries out there that simply "work". By this I mean, for example, you just do "Wire.begin()" or "Serial.begin(9600)" without having to declare an instance of an object or anything.
I wrote a very simple skeleton and tried to compile it but was not successful. I'm still getting used to C++, and I know that there is the -> operator as well, but I don't fully understand how that one works, and given that most libraries out there can be used with the dot notation, I'm not sure what I'm doing wrong. From my code you can see what I'm trying to accomplish.
One thing I also tried was to add "static" to the methods in both the header and the cpp file, but this did not change anything. I also tried looking at source code from a few existing libraries but I couldn't deduce what they were doing differently from me.
Here is a minimal "non-working" example:
Main sketch:
#include "mylib.h"
void setup() {
mylib.begin();
}
void loop() {
mylib.dostuff();
}
Library header:
#include <Arduino.h>
class mylib {
void begin();
void dostuff();
}
Library code:
#include "mylib.h"
void mylib::begin() {
pinMode(LED_BUILTIN, OUTPUT);
// blink the led a few times
for (int i = 0; i < 5; i++) {
digitalWrite(LED_BUILTIN, LOW);
delay(100);
digitalWrite(LED_BUILTIN, HIGH);
delay(100);
}
digitalWrite(LED_BUILTIN, LOW);
}
void mylib::dostuff() {
// blink the LED
digitalWrite(LED_BUILTIN, HIGH);
delay(200);
digitalWrite(LED_BUILTIN, LOW);
delay(800);
}
This won't compile, and the errors are:
C:\Users\fmillion\src\arduino_lib_test\arduino_lib_test.ino: In function 'void setup()':
arduino_lib_test:4:8: error: expected unqualified-id before '.' token
mylib.begin();
^
C:\Users\fmillion\src\arduino_lib_test\arduino_lib_test.ino: In function 'void loop()':
arduino_lib_test:8:8: error: expected unqualified-id before '.' token
mylib.dostuff();
^
exit status 1
expected unqualified-id before '.' token
Thank you!