Here is my program:
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <unistd.h>
#include <err.h>
#include <errno.h>
#include <linux/types.h>
#include <linux/i2c.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#define I2C_SLAVE 0x0703
int main(int argc, char **argv)
{
uint8_t data, i2c_device_address = 0x21,
i2c_register_address = 0x01;
int file, rc;
//Open I2C
file = open("/dev/i2c-1", O_RDWR);
if (file < 0)
err(errno, "Tried to open /dev/i2c-1");
// I want to work with I2C Register at I2C Address 0x12
rc = ioctl(file, I2C_SLAVE, i2c_register_address);
if (rc < 0)
err(errno, "Tried to set device address '0x%02x'",
i2c_device_address);
// Read Content of I2C Register at I2C Address 0x12
rc = read(file, &data, 1);
if (rc < 0)
err(errno, "Tried to read device at address '0x%02x'",
i2c_device_address);
// Print the Result
// Expected (Default) Value = 0x80
// What i got = 0x00
printf("/dev/i2c-1: device 0x%02x at address 0x%02x: 0x%02x\n",
i2c_device_address, i2c_register_address, data);
// Terminal Output:
// /dev/i2c-1: device 0x21 at address 0x01: 0x00
return 0;
}
I have the ov7670 camera and i am trying to read some registers for warm up.
But i always get the same result: 0x00. The datasheet of the camera tells me that 0x80 is the default value for this register.
When my camera isn't even connected to my Raspberry PI it still prints the same output when i run my program. There are not even errors.
I used the command i2cdetect -r 1 and i got correct output.
So the device must be ok and properly connected.
I want to know how can i read and write to i2c registers with the basic Linux read, write & ioctl functions?
UPDATE Now I check the return value of the read function and it says Remote I/O error
The ioctl
takes the device address as the third parameter, not the register:
rc = ioctl(file, I2C_SLAVE, i2c_device_address);
Then, you need a write-read combination, first writing the register you want to read then do the read
.
And you have to check the return value of the read
. It needs to be 1
or the read
failed.