Skip to content
Advertisement

Arduino and cpp file communication

I’ve connected a sensor with my Arduino board and am running a sketch which retrieves some data from the sensor and stores it in 4 double variables. I need to access these 4 variables from another .cpp file.

To do this I’ve created a common header file for both which declares 4 extern variables. These are then defined in the arduino sketch. The problem with this is that when I try to access the variables from the .cpp file, a compiler error is stating that they are undefined.

The arduino sketch :

#include <Wire.h>
#include <Adafruit_Sensor.h>
#include <Adafruit_BNO055.h>
#include <utility/imumaths.h>
#include <varDec.h>

#define BNO055_SAMPLERATE_DELAY_MS (1000)

double x,y,z,w;

Adafruit_BNO055 bno = Adafruit_BNO055();

void setup()
{
  Serial.begin(9600);

  if(!bno.begin())
  {
    Serial.println("Not connected");
    while(1);
  }

  bno.setExtCrystalUse(false);

}

void loop()
{
  imu::Quaternion quat = bno.getQuat();

  x = quat.x();
  y = quat.y();
  z = quat.z();
  w = quat.w();

  uint8_t system, gyro, accel, mag = 0;
  bno.getCalibration(&system, &gyro, &accel, &mag);  

  delay(BNO055_SAMPLERATE_DELAY_MS);

}

The cpp file :

#include <unistd.h> // sleep()
#include <stdio.h>  // fopen(), fclose(), fprintf(), perror()
#include <stdlib.h> // exit() and EXIT_FAILURE
#include <iostream>
#include "/home/matthew/sketchbook/libraries/Custom/varDec.h"

using namespace std;

int main()
{   
   cout << x; 
   getchar();

   getchar();

    return(0);
} // end function: main

And the header :

extern double x;
extern double y;
extern double z;
extern double w;

Advertisement

Answer

From the structure of what I am reading, I guess, what you call “another .cpp file” is a program that runs on a computer….

If that is the case, then what you are trying to do will never work. variables, are named spaced of allocated memory. and a program running on a computer will not get access to allocated memory on the arduino.

The easiest way to get the values from the sensors to the program running on your computer is to program the arduino to write the values to the serial port. (here you find good examples on how to send values of different format to the serial port : https://www.arduino.cc/en/serial/print )

And the program running on your computer should read the serial port for the expected values. reading the serial port on your computer, isn’t a hard task. but it is system dependant. there is plenty of doc on the internet)

Good luck my friend 😉

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement