I’m working on a Simultaneous Localization and Mapping (SLAM) project that requires a connection between a remote car and my laptop running Python. I wrote a C++ class that successfully creates a socket connection and exchanges messages between an ESP32C6 and a Python script. So far, so good.
Next, I attempted to move the class from inline code to an Arduino library. However, when the class is loaded from the library, the code crashes the ESP32 on the first method call.
To better understand the issue, I wrote a small test class to identify my mistake. Here is the test code, foobar:
//#include <foobar.h>
#include <Arduino.h>
#include <string>
class foobar {
public:
foobar() {
//Serial.println(" In constructor in FooBar");
};
bool foo (std::string xx){
Serial.println("In Foo in FooBar");
return true;
};
int bar(int i){
Serial.println("In bar in FooBar");
return i;
};
};
foobar* fb;
void setup() {
Serial.begin(19200);
delay(1000);
fb = new foobar();
}
void loop() {
Serial.println("In loop..");
bool tf = fb->foo("foo");
Serial.println(tf);
int i = fb->bar(10);
Serial.println(i);
delay(5000);
}
When executed inline, the code produces the expected output:
In loop..
In Foo in FooBar
1
In bar in FooBar
10
Next, I added a foobar folder to the Libraries folder and created foobar.h and foobar.cpp as shown below. In the code above, I commented out the inline class and uncomment the #include <foobar.h> to try the Library test.
#include <string>
class foobar {
public:
foobar() {};
bool foo (std::string xx){};
int bar(int i){};
};
#include <Arduino.h>
#include <string>
//#include <foobar.h>
class foobar {
public:
foobar() {
};
bool foo (std::string xx){
Serial.println("In Foo in FooBar");
return true;
};
int bar(int i){
Serial.println("In bar in FooBar");
return i;
};
};
This code compiles and loads correctly on the ESP32C6 board but crashes with the following message:
Guru Meditation Error: Core 0 panic'ed (Load access fault). Exception was unhandled.
To be thorough, I ran the same test on an Arduino R4 WiFi. When run inline, the code operates correctly. However, when loaded from the foobar library folder, it does not crash but produces invalid results:
In loop..
0
0
In loop..
0
My incomplete understanding is that the library .cpp code is compiled and linked separately, whereas the inline class code is compiled simultaneously.
I suspect this is some linking or address pointer issue, but I’m at a loss as to how to resolve it. I have reviewed existing library implementations, the Arduino Forum, various examples, and numerous YouTube videos, but to no avail. I’m stuck (and I’m sure the solution is embarrassingly obvious).
Thanks in advance for helping me advance my understanding.