I2cwrite.c

/* a simple program to write on i2c bus* * Fabien Marteau <fabien.marteau@armadeus.com> * * inspired from : * ch7024: manage the Svideo controller CH7024 * author: thom25@users.sourceforge.net * * ** THE ARMADEUS PROJECT ** ** Copyright (C) year The source forge armadeus project team ** ** 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 2 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, write to the Free Software ** Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. ** */#include <stdio.h>#include <fcntl.h>#include <errno.h>#include <unistd.h>#include <stdlib.h>#include <string.h>#include <linux/i2c.h> #include <linux/i2c-dev.h>#include <sys/ioctl.h>intfd;/* Write a byte on the I2C bus @param fd: file descriptor of the device @param reg: register to access @param value: value to write @return : -1 in case of error otherwise 0 */intwrite_byte(intfd,unsignedcharaddr,unsignedcharreg,unsignedcharvalue){unsignedcharbuf[2]={reg,value};// initialise a data buffer with // address and data// create an I2C write messagestructi2c_msgmsg={addr,0,sizeof(buf),buf};// create a I2C IOCTL requeststructi2c_rdwr_ioctl_datardwr={&msg,1};if(ioctl(fd,I2C_RDWR,&rdwr)<0){printf("Write error\n");return-1;}return0;}/* i2cwrite i2c-devfile addr value*/intmain(intargc,char**argv){unsignedcharbuf;unsignedcharaddr;unsignedcharsubaddr;unsignedcharvalue;if(argc!=5){printf("wrong args numbers\nsyntaxe (value in hexa) :\ni2cwrite i2c-devfile addr subaddr value\n");return-1;}fd=open(argv[1],O_RDWR);if(fd<0){printf("can't open %s\n",argv[1]);return-1;}addr=(unsignedchar)strtol(argv[2],(char**)NULL,16);subaddr=(unsignedchar)strtol(argv[3],(char**)NULL,16);buf=(unsignedchar)strtol(argv[4],(char**)NULL,16);write_byte(fd,addr,subaddr,buf);printf("Wrote component %02x at subaddress %02x -> %02x\n",addr,subaddr,buf);returnvalue;}