Using Sensors

The sensors inside the EV3 brick can be accessed trough the device file system at:

/sys/class/lego-sensor/sensor#/

were # can be 0 to N that correspond to the different sensors that are plugged into the EV3 brick. Notice that when a sensor is removed the device number is not freed and a new sensor entry will be created, therefore N can be larger than 3.

The following is an example of how to read from an I2C (NXT) sensor, specifically the Microinfinity XG1300L gyroscope that we use in several of our robots. This device is not automatically recognized by the EV3 brick. Users will have to load the correct driver using the following commands after logging in the brick:


sudo echo mi-xg1300l 0x01 > /sys/bus/i2c/devices/i2c-3/new_device

Assuming that the sensor has been identified as sensor1, we can use the following program to reset, and pull data from this device:

/*
* Robot Navigation Program
* www.robotnav.com
*
* (C) Copyright 2017 Lauro Ojeda
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

#include <fstream>
#include <iostream>

// see setting up instructions at README.txt
char XG1300L_VALUE[] = "/sys/class/lego-sensor/sensor1/value0";
char XG1300L_COMMAND[] = "/sys/class/lego-sensor/sensor1/command";
using namespace std;

int main()
{
string xg_value;
ofstream fd_command;
ifstream fd_value;

// Initialize device
fd_command.open(XG1300L_COMMAND);
if(!fd_command.is_open())
{
cout << "Failed to open file command";
return -1; //Failed to open device
}
cout << "Reseting";
fd_command << "RESET" << endl;
sleep(1);
fd_command.close();

// Read data
while(1)
{
fd_value.open(XG1300L_VALUE);
fd_value >> xg_value;
cout << xg_value << endl;
fd_value.close();
}
return 0;
}