add battery monitor skeleton c code
This commit is contained in:
parent
120860328f
commit
3e5c36c23f
4
Makefile
4
Makefile
@ -1,7 +1,7 @@
|
||||
SOURCE = main.c
|
||||
CC = arm-linux-gnueabi-gcc
|
||||
CC = aarch64-linux-gnu-gcc
|
||||
FLAG = --static -o
|
||||
OUT = I2C_scan.elf
|
||||
OUT = I2C_scan
|
||||
main:${SOURCE}
|
||||
${CC} ${SOURCE} ${FLAG} ${OUT}
|
||||
clean:
|
||||
|
12
i2c_driver/Makefile
Normal file
12
i2c_driver/Makefile
Normal file
@ -0,0 +1,12 @@
|
||||
SOURCE = main.c
|
||||
CC = aarch64-linux-gnu-gcc
|
||||
FLAG = --static -o
|
||||
OUT = I2C_out
|
||||
main:${SOURCE}
|
||||
${CC} ${SOURCE} ${FLAG} ${OUT}
|
||||
clean:
|
||||
rm -r ${OUT}
|
||||
.PHONY:clean
|
||||
|
||||
|
||||
|
76
i2c_driver/main.c
Normal file
76
i2c_driver/main.c
Normal file
@ -0,0 +1,76 @@
|
||||
#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 0x50 // Example I2C device address (7-bit 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;
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user