forked from static-void/rtd266x_programmer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
i2clinux.cpp
83 lines (73 loc) · 1.93 KB
/
i2clinux.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
#include "i2c.h"
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
extern "C"
{
#include <linux/i2c-dev.h>
}
static int file;
static char filename[20];
bool
InitI2C(int adapter_nr) {
snprintf(filename, 19, "/dev/i2c-%d", adapter_nr);
file = open(filename, O_RDWR);
if (file < 0) {
/* ERROR HANDLING; you can check errno to see what went wrong */
fprintf(stderr, "Error: could not open %s\n", filename);
return false;
}
return true;
}
bool
CloseI2C() {
if (close(file) < 0) {
fprintf(stderr, "Error: could not close %s\n", filename);
return false;
}
return true;
}
bool
SetI2CAddr(uint8_t addr) {
if (ioctl(file, I2C_SLAVE, addr) < 0) {
/* ERROR HANDLING; you can check errno to see what went wrong */
fprintf(stderr, "Error: could not set slave address to %x\n", addr);
return false;
}
return true;
}
bool
WriteReg(uint8_t reg, uint8_t value) {
if (i2c_smbus_write_byte_data(file, reg, value) < 0) {
/* fprintf(stderr, "Error: could not write to register %d\n", reg); */
return false;
}
return true;
}
uint8_t
ReadReg(uint8_t reg) {
int32_t result;
result = i2c_smbus_read_byte_data(file, reg);
/* if ((result = i2c_smbus_read_byte_data(file, reg)) == -1)
fprintf(stderr, "Error: could not read from register %d\n", reg); */
return (uint8_t)result;
}
int32_t
ReadBytesFromAddr(uint8_t reg, uint8_t* dest, uint8_t len) {
int read;
if ((read = i2c_smbus_read_i2c_block_data(file, reg, len, dest)) == -1) {
/* fprintf(stderr, "Error: could not read block from register %d\n", reg); */
return -1;
}
return read;
}
bool
WriteBytesToAddr(uint8_t reg, uint8_t* values, uint8_t len) {
//if (i2c_smbus_write_block_data(file, reg, len, values) < 0) {
if (i2c_smbus_write_i2c_block_data(file, reg, len, values) < 0) {
/* fprintf(stderr, "Error: could not write block data to register %d\n", reg); */
return false;
}
return true;
}