83 lines
1.8 KiB
C
83 lines
1.8 KiB
C
/*
|
|
Author : Siva prakasam V
|
|
Date : 05/01/25
|
|
Title : I2C driver for Battery Monitor
|
|
*/
|
|
|
|
#include <stdio.h>
|
|
#include <stdint.h>
|
|
#include <stdlib.h>
|
|
#include <unistd.h>
|
|
#include <fcntl.h>
|
|
#include <sys/ioctl.h>
|
|
#include <linux/i2c-dev.h>
|
|
|
|
#define I2C_BUS "/dev/i2c-1" // I2C bus device
|
|
#define I2C_ADDRESS 0x6B // I2C device address
|
|
|
|
// Function to write a byte to the I2C device
|
|
int i2c_write(int file, uint8_t reg, uint8_t value) {
|
|
uint8_t buffer[2];
|
|
buffer[0] = reg; // Register address
|
|
buffer[1] = value; // Data to write
|
|
|
|
if (write(file, buffer, 2) != 2) {
|
|
perror("Failed to write to the I2C bus");
|
|
return -1;
|
|
}
|
|
|
|
return 0;
|
|
}
|
|
|
|
// Function to read a byte from the I2C device
|
|
int i2c_read(int file, uint8_t reg, uint8_t *data) {
|
|
if (write(file, ®, 1) != 1) { // Send the register address
|
|
perror("Failed to write register address to the I2C bus");
|
|
return -1;
|
|
}
|
|
|
|
if (read(file, data, 1) != 1) { // Read the data
|
|
perror("Failed to read from the I2C bus");
|
|
return -1;
|
|
}
|
|
|
|
return 0;
|
|
}
|
|
|
|
int main() {
|
|
int file;
|
|
uint8_t data;
|
|
|
|
// Open the I2C bus
|
|
if ((file = open(I2C_BUS, O_RDWR)) < 0) {
|
|
perror("Failed to open the I2C bus");
|
|
exit(1);
|
|
}
|
|
|
|
// Connect to the I2C device
|
|
if (ioctl(file, I2C_SLAVE, I2C_ADDRESS) < 0) {
|
|
perror("Failed to connect to the I2C device");
|
|
close(file);
|
|
exit(1);
|
|
}
|
|
|
|
// Write a value to the device
|
|
if (i2c_write(file, 0x00, 0x42) < 0) {
|
|
close(file);
|
|
exit(1);
|
|
}
|
|
|
|
// Read a value from the device
|
|
if (i2c_read(file, 0x00, &data) < 0) {
|
|
close(file);
|
|
exit(1);
|
|
}
|
|
|
|
printf("Read value: 0x%02X\n", data);
|
|
|
|
// Close the I2C bus
|
|
close(file);
|
|
return 0;
|
|
}
|
|
|