◆ 라즈베리파이에서 C 언어를 사용하여 I2C 통신을 하려면 raspi-config로 I2C를 활성화하고 wiringPi 또는 i2c-dev 라이브러리를 사용한다.
◆ 디바이스 파일(/dev/i2c-1)을 열어 ioctl로 슬레이브 주소를 설정한 다음에 read/write 함수로 데이터를 송수신한다.
◎ 패키지 설치
$ sudo apt-get install i2c-tools libi2c-dev
int main() {
int file;
char *filename = "/dev/i2c-1"; // 라즈베리 파이 2, 3, 4, 5는 1 사용
int addr = 0x48; // 슬레이브 디바이스 주소 (예: 센서)
// 1. I2C 버스 열기
if ((file = open(filename, O_RDWR)) < 0) {
perror("Failed to open the i2c bus");
return 1;
}
// 2. 슬레이브 주소 설정
if (ioctl(file, I2C_SLAVE, addr) < 0) {
perror("Failed to acquire bus access and/or talk to slave");
return 1;
}
// 3. 데이터 쓰기 (예: 레지스터 0x01에 0xFF 값 쓰기)
char buf[2];
buf[0] = 0x01;
buf[1] = 0xFF;
if (write(file, buf, 2) != 2) {
perror("Failed to write to the i2c bus");
}
// 4. 데이터 읽기
char reg = 0x00; // 읽을 레지스터 주소
write(file®, 1); // 레지스터 위치 지정
if (read(file, buf, 1) != 1) {
perror("Failed to read from the i2c bus");
} else {
printf("Data: %d\n", buf[0]);
}
■ WiringPi C언어 I2C 주요 함수
int wiringPiI2CSetup(int devId): I2C 장치 초기화. devId는 슬레이브 주소(예: 0x68)이며파일 디스크립터(fd)를 반환.
int wiringPiI2CRead(int fd): 8비트 데이터 읽기.
int wiringPiI2CWrite(int fd, int data): 8비트 데이터 쓰기.
int wiringPiI2CWriteReg8(int fd, int reg, int data): 특정 레지스터에 8비트 쓰기.
int wiringPiI2CReadReg8(int fd, int reg): 특정 레지스터에서 8비트 읽기.