Processor

【라즈베리파이】 wiringPi C 언어 : I2C 실험

작성자 임베디드코리아 작성일26-02-17 18:26 조회99회 댓글0건
◆ 라즈베리파이에서 C 언어를 사용하여 I2C 통신을 하려면 raspi-config로 I2C를 활성화하고 wiringPi 또는 i2c-dev 라이브러리를 사용한다.
◆ 디바이스 파일(/dev/i2c-1)을 열어 ioctl로 슬레이브 주소를 설정한 다음에 read/write 함수로 데이터를 송수신한다.

◎ 패키지 설치
$ sudo apt-get install i2c-tools libi2c-dev

--->>> 예제  :  i2c_test.c    >>>-------------------------------
#include <stdio.h>
#include <fcntl.h>
#include <linux/i2c-dev.h>
#include <sys/ioctl.h>
#include <unistd.h>

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]);
    }

    close(file);
    return 0;
}
------------------------------------------------------------------------------
$ gcc -o i2c_test i2c_test.c
$ sudo ./i2c_test

■ 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비트 읽기.

--->>>  예제  i2c_wiringPI_test.c  <<<--------------------------------
#include <wiringPiI2C.h>
#include <stdio.h>

int main() {
    int fd;
    int deviceAddress = 0x68; // 장치의 I2C 주소
   
    // 1. I2C 장치 설정 (fd 반환)
    fd = wiringPiI2CSetup(deviceAddress);
    if (fd == -1) {
        printf("I2C 장치 설정 실패\n");
        return -1;
    }

    // 2. 데이터 쓰기 (예: 0x00 레지스터에 0x01 설정)
    wiringPiI2CWriteReg8(fd, 0x00, 0x01);

    // 3. 데이터 읽기 (예: 0x01 레지스터에서 읽기)
    int data = wiringPiI2CReadReg8(fd, 0x01);
    printf("읽은 데이터: %d\n", data);

    return 0;
}
-----------------------------------------------------------------------------
$ gcc -o i2c_test i2c_test.c -lwiringPi
$ sudo ./i2c_test