使用C ++从LEGO EV3传感器获取数据?

时间:2014-06-16 23:06:06

标签: c++ lego mindstorms

我正在尝试使用C ++与LEGO Mindstorms EV3砖进行通信。我克隆了ev3sources repo,这允许我通过蓝牙实现这一点 - 例如,要启动连接到端口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的任何传感器捕获的数据。基于the repo examples我知道我需要看起来像这样的东西:

#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);
}

但缺少某些内容 - 上面的代码段不会返回任何错误,但我不知道传感器数据在哪里。那么,我该如何检索它呢?我想它也是通过蓝牙发回来的,但是我该如何捕获呢?

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

2 个答案:

答案 0 :(得分:1)

您需要在写完后阅读bt。与您发送的数据一样,前两个字节是大小,因此首先读取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
}

答案 1 :(得分:0)

可能不是您正在寻找的答案,但可能对发现自己处于相同情况的人有用:

作为c4ev3的一部分,我们开源了我们的EV3 uploader,它也可用于向设备发送与连接无关的命令。

查看https://github.com/c4ev3/ev3duder/blob/master/moveEv3.pl以获取示例。

这样做的好处是,您的代码不必担心连接方法:通过蓝牙,Wi-Fi或USB实现连接是否完全透明。您只需打开2个管道到./ev3duder tunnel并使用它们。

相关问题