본문 바로가기

개발 이야기/임베디드 개발

아두이노 i2c 라이브러리인 Wire 라이브러리를 사용하지 않고 i2c_write / i2c_read 함수 만들기

728x90

 

 

아래는 아두이노 i2c 라이브러리인 Wire 라이브러리를 사용하지 않고, hali2cwritebytes()hali2creadbytes() 함수를 이용하여 I2C 통신을 구현하는 예시 코드입니다.

#include <Wire.h>

#define SDA_PIN 20
#define SCL_PIN 21

void i2c_init() {
  pinMode(SDA_PIN, OUTPUT);
  pinMode(SCL_PIN, OUTPUT);
}

void i2c_start() {
  digitalWrite(SDA_PIN, HIGH);
  digitalWrite(SCL_PIN, HIGH);
  digitalWrite(SDA_PIN, LOW);
  digitalWrite(SCL_PIN, LOW);
}

void i2c_stop() {
  digitalWrite(SDA_PIN, LOW);
  digitalWrite(SCL_PIN, HIGH);
  digitalWrite(SDA_PIN, HIGH);
}

bool i2c_write(uint8_t data) {
  for (uint8_t i = 0; i < 8; i++) {
    digitalWrite(SDA_PIN, (data & (1 << (7 - i))) != 0);
    digitalWrite(SCL_PIN, HIGH);
    digitalWrite(SCL_PIN, LOW);
  }
  pinMode(SDA_PIN, INPUT);
  digitalWrite(SCL_PIN, HIGH);
  bool ack = digitalRead(SDA_PIN) == LOW;
  digitalWrite(SCL_PIN, LOW);
  pinMode(SDA_PIN, OUTPUT);
  return ack;
}

uint8_t i2c_read(bool ack) {
  uint8_t data = 0;
  pinMode(SDA_PIN, INPUT);
  for (uint8_t i = 0; i < 8; i++) {
    digitalWrite(SCL_PIN, HIGH);
    data |= digitalRead(SDA_PIN) << (7 - i);
    digitalWrite(SCL_PIN, LOW);
  }
  pinMode(SDA_PIN, OUTPUT);
  digitalWrite(SDA_PIN, !ack);
  digitalWrite(SCL_PIN, HIGH);
  digitalWrite(SCL_PIN, LOW);
  digitalWrite(SDA_PIN, HIGH);
  return data;
}

void hali2cwritebytes(uint8_t address, uint8_t* data, uint8_t length) {
  i2c_start();
  i2c_write(address << 1);
  for (uint8_t i = 0; i < length; i++) {
    i2c_write(data[i]);
  }
  i2c_stop();
}

void hali2creadbytes(uint8_t address, uint8_t* data, uint8_t length) {
  i2c_start();
  i2c_write((address << 1) | 0x01);
  for (uint8_t i = 0; i < length; i++) {
    bool ack = i < length - 1;
    data[i] = i2c_read(ack);
  }
  i2c_stop();
}

 

(출처1)

출처는 Free ChatGPT 입니다.

 

 

그럼,

    공유합니다.

 

728x90