Simple I2C Interface

Lego_NXT_US_sensor
Many devices that work with the Lego NXT communicate using the I2C interface. Although the Lego EV3 uses in mainly the RS232 serial communication, it can still detect when an I2C devices is plugged in the brick and set the communication protocol accordingly. The following program demonstrates how to setup a basic I2C communication interface. This is useful for devices that don’t require any specific configuration such as the Lego NXT Ultrasonic Sensor.

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

//Runtime constants
const int MAX_SAMPLES  = 100;
const char IIC_PORT = 0x0; //EV3 label minus 1

int main()
{
	//DEFINE VARIABLES
	int iic_device_file;
	IIC     *pIic;
	int i;
	
	//INITIALIZE DEVICE
	//Open the device file
	if((iic_device_file = open(IIC_DEVICE_NAME, O_RDWR | O_SYNC)) == -1)
	{
		printf("Failed to open IIC device\n");
		return -1; 
	}
	pIic  =  (IIC*)mmap(0, sizeof(UART), PROT_READ | PROT_WRITE, MAP_FILE | MAP_SHARED, iic_device_file, 0);
	if (pIic == MAP_FAILED)
  {
		printf("Mapping IIC device failed\n");
		return -1;
	}
	printf("IIC Device is ready\n");

	//PROCESS SENSOR DATA
	//Read IIC device state
	for(i = 0;i<MAX_SAMPLES;i++)
	{
		printf("Value: %d \n", (unsigned char)pIic->Raw[IIC_PORT][pIic->Actual[IIC_PORT]][0]);
		sleep(1);
	}

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