1

C++ を使用して LEGO Mindstorms EV3 ブロックと通信しようとしています。私はev3sources repoのクローンを作成しました。これにより、Bluetooth 経由でそれを行うことができます。たとえば、ポート A に接続されたモーターを開始するには、次のようにします。

#include <unistd.h>
#include <fcntl.h>
#include "ev3sources/lms2012/c_com/source/c_com.h"

int main()
{

    // start motor on port A at speed 20
    unsigned const char start_motor[] {12, 0, 0, 0,
        DIRECT_COMMAND_NO_REPLY,
        0, 0,
        opOUTPUT_POWER, LC0(0), LC0(0x01), LC0(20),
        opOUTPUT_START, LC0(0), LC0(0x01)};

    // send above command to EV3 via Bluetooth
    int bt = open("/dev/tty.EV3-SerialPort", O_WRONLY);
    write(bt, start_motor, 14);
    close(bt);
}

しかし、EV3 ブリックからデータを取り戻すにはどうすればよいでしょうか? たとえば、ポート 1 に接続されているセンサーによってキャプチャされたデータを読み取りたいとします。レポの例に基づいて、次のようなものが必要であることがわかります。

#include <unistd.h>
#include <fcntl.h>
#include "ev3sources/lms2012/c_com/source/c_com.h"

int main()
{

    // read sensor on port 1
    unsigned const char read_sensor[] {11, 0, 0, 0,
        DIRECT_COMMAND_REPLY,
        0, 0,
        opINPUT_READ, LC0(0), LC0(0), LC0(0), LC0(0), GV0(0)};

    // send above command to EV3 via Bluetooth
    int bt = open("/dev/tty.EV3-SerialPort", O_WRONLY);
    write(bt, read_sensor, 13);
    close(bt);
}

しかし、何かが欠けています。上記のスニペットはエラーを返しませんが、センサー データがどこにあるのかわかりません。では、どのように取得すればよいでしょうか。Bluetooth経由でも送信されると思いますが、どうすればそれをキャプチャできますか?

(OS X 10.9.3、Xcode 5.1.1、EV3 [31313])

4

2 に答える 2

1

書いた後に読む必要がありbtます。送信するデータと同様に、最初の 2 バイトがサイズであるため、最初に 2 バイトを読み取り、それを使用して、さらに読み取る必要があるバイト数を計算します。

#define MAX_READ_SIZE 255
unsigned char read_data[MAX_READ_SIZE];
int read_data_size;

// existing code
// ...
write(bt, read_sensor, 13);
read(bt, read_data, 2);
read_size = read_data[0] + read_data[1] << 8;
read(bt, read_data, read_size);
close(bt);
// decode the data
// ...

編集:コメントに基づいて完全なコード

#include <unistd.h>
#include <fcntl.h>
#include "ev3sources/lms2012/c_com/source/c_com.h"

#define MAX_READ_SIZE 255

int main()
{
    unsigned char read_data[MAX_READ_SIZE];
    int read_data_size;

    // read sensor on port 1
    unsigned const char read_sensor[] {11, 0, 0, 0,
        DIRECT_COMMAND_REPLY,
        1, 0, // 1 global variable
        opINPUT_READ, LC0(0), LC0(0), LC0(0), LC0(0), GV0(0)};

    // send above command to EV3 via Bluetooth
    int bt = open("/dev/tty.EV3-SerialPort", O_RDWR);
    write(bt, read_sensor, 13);
    read(bt, read_data, 2);
    read_size = read_data[0] + read_data[1] << 8;
    read(bt, read_data, read_size);
    close(bt);
    // TODO: check that command was successful and so something with data
}
于 2014-06-17T00:42:22.917 に答える