Serial Interface

The Lego EV3 uses a TTL RS232 serial interface to communicate with external sensors. The following program can be used to read from sensors such as the gyroscope, sonar and color sensors.

/*
* Robot Navigation Program
* www.robotnav.com
*
* (C) Copyright 2013 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
#include
#include <sys/mman.h>
#include "lms2012.h"

const char PORT = 0x0; //EV3 label minus 1
const int MAX_SAMPLES = 100;
int main()
{
//DEFINE VARIABLES
int file;
UART *pUart; //UART porte user level handler
int i;

//INITIALIZE DEVICE
//Open the device uart device file
if((file = open(UART_DEVICE_NAME, O_RDWR | O_SYNC)) == -1)
{
printf("Failed to open device\n");
return -1;
}
//Map kernel device to be used at the user space level
pUart = (UART*)mmap(0, sizeof(UART), PROT_READ | PROT_WRITE, MAP_FILE | MAP_SHARED, file, 0);
if (pUart == MAP_FAILED)
{
printf("Failed to map device\n");
return -1;
}

//PROCESS SENSOR DATA
printf("Device is ready\n");
for(i = 0;i<MAX_SAMPLES;i++) { printf("UART Value: %d\n", (unsigned char)pUart->Raw[PORT][pUart->Actual[PORT]][0]);
sleep(1);
}

//CLOSE DEVICE
printf("Clossing device\n");
close(file);
return 0;
}