0

What I am trying to accomplish is either return an array of bytes in a function so that I can do:

byte array[8] = function();

I am using my self made library to get values with the i2c bus. This is the library:

#ifndef MPULIBRARY_HPP
#define MPULIBRARY_HPP
#include "hwlib.hpp"

namespace mpulibrary{
class mpumanager
{
private:
    hwlib::i2c_bus_bit_banged_scl_sda bus;
    byte startregister[2] = {0x6B, 0};
    byte adress = 0x68;
    byte xregister[8] = {0x3B};
    byte yregister[8] = {0x3D};
    byte zregister[8] = {0x3F};
public:

    mpumanager(hwlib::i2c_bus_bit_banged_scl_sda bus):
        bus(bus)
    {}

    void startup(){
        bus.write(adress, startregister, 2);
    }   

    byte getXaxis(){
        bus.write(adress, xregister, 1);
        bus.read(adress, xregister, 2);
        return xregister[8];
    }
    byte getYaxis(){
        bus.write(adress, yregister, 1);
        bus.read(adress, yregister, 2);
        return yregister[8];
    }
    byte getZaxis(){
        bus.write(adress, zregister, 1);
        bus.read(adress, zregister, 2);
        return zregister[8];
    }

};
};
#endif // MPULIBRARY_HPP

My other code:

 auto manager = mpulibrary::mpumanager(i2c_bus);

 for(;;){
    manager.startup();

    byte ydata[8] = {};
    manager.getYaxis(ydata[8]);


    byte zdata[8] = {0x3F};
    i2c_bus.write(adress, zdata, 1);
    i2c_bus.read(adress, zdata, 2);

    int16_t yaxis = 0;
    int16_t zaxis = 0;
    yaxis = (ydata[0] << 8) + ydata[1];
    zaxis = (zdata[0] << 8) + zdata[1];

    hwlib::cout << "Y: " << yaxis << " Z:" << zaxis << "\n";
    hwlib::wait_ms(100);

 }

I hope someone can provide me an answer. Thanks in advance!

2 Answers 2

2

byte array[8] = function();

You cannot directly with C-array.
You have to wrap it in a class (as std::array<byte, 8>).

byte xregister[8] = {0x3B};
byte getXaxis(){
    bus.write(adress, xregister, 1);
    bus.read(adress, xregister, 2);
    return xregister[8];
}

You may return reference to array:

byte xregister[8] = {0x3B};
using byte_array = byte[8]; // typedef to avoid strange syntax in return type

byte_array& getXaxis(){
    bus.write(adress, xregister, 1);
    bus.read(adress, xregister, 2);
    return xregister;
}

and use it:

auto& xAxis = manager.getXaxis();
Sign up to request clarification or add additional context in comments.

Comments

1

You could pass an array by reference if you could transform your function as:

template<int N>
void function(byte (&array)[N]) {

}

Or if you want to restrict the size as (e.g., 8):

void function(byte (&array)[8]) {

}

You can't return a raw array because C-style raw arrays are not copy-able.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.