c++ interrupt handling data

c++ interrupt handling data

Sorry for the cryptic title, I wasn't quite sure how to make it without writing this post. I'm working on a raspberry Pi project that is dealing with motor drives and interrupts. The issue I'm having is getting the data from the interrupts. I'm trying to keep this all in C++, so am struggling with static data.

motor.h

class Motors
{
  public:
  Motors()
  {...}
  static void tickA2D( Motors *myObj );
}

motor.cpp

// telemetry 
static volatile float Vbatt;

void Motors::tickA2D( Motors *myObj ) {
  Vbatt = telem; // this works fine
}

lawnmower.cpp

std::string elecData = "{\"vbatt\":" + std::to_string(mtr->Vbatt)...  //fails
std::string elecData = "{\"vbatt\":" + std::to_string(Motors::Vbatt)...  //fails

console:

lawnmower.cpp:152: undefined reference to `Motors::Vbatt'

How can I access the variable Vbatt from lawnmower.cpp? I have 3 other variables as well, but I'm trying to keep this simple.

Answer

First, you should declare Vbatt in the class definition in motor.h .

class Motors
{
public:
    Motors() { ... }

    static void tickA2D(Motors *myObj);

    // Add this line to declare Vbatt
    static volatile float Vbatt;
};

Next, you should define Vbatt in motor.cpp.

#include "motor.h"

// actually define the static member here
volatile float Motors::Vbatt = 0.0;

Last, you can access it in lawnmower.cpp.

std::string elecData = "{\"vbatt\":" + std::to_string(Motors::Vbatt) + "}";

Note:

You marked Vbatt as volatile, which is great for interrupt/shared memory stuff. But:

  • volatile tells the compiler not to optimize out reads and writes (because the value can change outside normal program flow like in ISRs).

  • It does not make access thread-safe (so don’t forget atomic or mutexes if needed later, depending on complexity)

Enjoyed this question?

Check out more content on our blog or follow us on social media.

Browse more questions