-
Notifications
You must be signed in to change notification settings - Fork 21
/
i2c.c
88 lines (75 loc) · 2.02 KB
/
i2c.c
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
83
84
85
86
87
88
/*
FMBerry - an cheap and easy way of transmitting music with your Pi.
Copyright (C) 2011-2013 by Manawyrm
Copyright (C) 2013-2014 by Andrey Chilikin (https://github.com/achilikin)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "i2c.h"
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <alloca.h>
#include <memory.h>
#include <linux/i2c-dev.h>
int i2c_init(uint8_t bus, uint8_t address)
{
int fd;
char bus_name[64];
sprintf(bus_name, "/dev/i2c-%u", bus);
if ((fd = open(bus_name, O_RDWR)) < 0)
{
printf("Failed to open i2c port\n");
return -1;
}
if (i2c_select(fd, address) < 0) {
printf("Unable to get bus access to talk to slave\n");
close(fd);
return -1;
}
return fd;
}
int i2c_select(int dev, uint8_t address)
{
return ioctl(dev, I2C_SLAVE, address);
}
int i2c_send_data(int dev, uint8_t addr, uint8_t *data, uint32_t len)
{
uint8_t *buf = (uint8_t *)alloca(len+1);
memcpy(buf +1, data, len);
buf[0] = addr;
len++;
if (write(dev, buf, len) != len)
return -1;
return 0;
}
int i2c_send(int dev, uint8_t addr, uint8_t data)
{
char buf[2];
buf[0] = addr;
buf[1] = data;
if ((write(dev, buf, 2)) != 2) {
return -1;
}
return 0;
}
// send 16 bit, MSB first
int i2c_send_word(int dev, uint8_t addr, uint8_t *data)
{
char buf[3];
buf[0] = addr;
buf[1] = data[1];
buf[2] = data[0];
if ((write(dev, buf, 3)) != 3) {
return -1;
}
return 0;
}