Difference between revisions of "I2cwrite.c"
From ArmadeusWiki
(New page: <source lang="c"> →a simple program to test accelerometer * * Fabien Marteau <fabien.marteau@armadeus.com>: #include <stdio.h> #include <fcntl.h> #include <errno.h> #include <unist...) |
|||
Line 1: | Line 1: | ||
<source lang="c"> | <source lang="c"> | ||
− | /* a simple program to | + | |
+ | /* a simple program to write on i2c bus* | ||
* Fabien Marteau <fabien.marteau@armadeus.com> | * Fabien Marteau <fabien.marteau@armadeus.com> | ||
+ | * | ||
+ | * Inspired from another code, but I don't remember who. | ||
*/ | */ | ||
Line 73: | Line 76: | ||
return value; | return value; | ||
} | } | ||
+ | |||
</source> | </source> |
Revision as of 10:46, 3 April 2008
/* a simple program to write on i2c bus*
* Fabien Marteau <fabien.marteau@armadeus.com>
*
* Inspired from another code, but I don't remember who.
*/
#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>
int fd;
/* 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
*/
int write_byte(int fd,unsigned char addr, unsigned char reg, unsigned char value)
{
unsigned char buf[2] = {reg,value}; // initialise a data buffer with
// address and data
// create an I2C write message
struct i2c_msg msg = {addr, 0, sizeof(buf), buf };
// create a I2C IOCTL request
struct i2c_rdwr_ioctl_data rdwr = { &msg, 1 };
#ifdef DEBUG_CH7024
printf("write ref %02X value %02X\n",reg, value);
#endif
if ( ioctl( fd, I2C_RDWR, &rdwr ) < 0 ){
printf("Write error\n");
return -1;
}
return 0;
}
/* i2cwrite i2c-devfile addr value*/
int main(int argc, char **argv){
unsigned char buf;
unsigned char addr;
unsigned char subaddr;
unsigned char value;
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 = (unsigned char )strtol(argv[2], (char **)NULL, 16);
subaddr = (unsigned char )strtol(argv[3], (char **)NULL, 16);
buf = (unsigned char )strtol(argv[4], (char **)NULL, 16);
write_byte(fd,addr, subaddr, buf);
printf("Wrote component %02x at subaddress %02x -> %02x\n",addr,subaddr,buf);
return value;
}