Arduino

아두이노간 I2C 통신 송신과 수신하기

작성자 임베디드코리아 작성일25-05-16 00:39 조회1,301회 댓글0건

첨부파일

■  I2C 통신을 위한장치는 마스터(Master)와 슬레이브(Slave)로 나눈다.
    ▶ 하나의 마스터에 다수의 슬레이브가 연결될 수 있음.
    ▶ 구별을 위해 각 슬레이브마다 고유한 주소 값을 갖도록 함.
    ▶ 슬레이브의 주소 값을 이용해 마스터는 한번에 하나의 슬레이브와 통신을 수행 함.

동영상 보기 : https://youtu.be/OFSyrVftw9o

------< I2C 통신 송신 소스 코드 > -------------------------------------------
#include<Wire.h>

void setup() {
  Wire.begin();
}

void loop() {
  Wire.beginTransmission(2); // 주소 1를 가진 슬레이브에 데이터 송신을 시작
  Wire.write("1");
  Wire.write("2");
  Wire.write("3");
  Wire.endTransmission(); // 슬레이브에 1, 2, 3이라는 데이터 송신
  delay(500);
}

------< I2C 통신 수신 소스 코드 > -------------------------------------------
#include<Wire.h>
void setup() {
  Serial.begin(9600);
  Wire.begin(2); // 슬레이브 자신을 1이라는 주소로 지정
  Wire.onReceive(receiveEvent); // 데이터를 수신했을 시 receiveEvent실행
}

void loop() {
}
void receiveEvent(int parameter) { // void형 매개 변수 int형형
  while(Wire.available() > 0) { // 버퍼에 데이터가 찼는지 확인
    char a = Wire.read(); // 버퍼에 찬 데이터 Read
    Serial.print(a);
    Serial.print(" ");
  } // 시리얼 모니터에 1, 2, 3이 출력됩니다.
}

---< I2C 통신 : 마스터에서 스레이브에 0~6 까지 전송 >------
#include <Wire.h>

byte x = 0;

void setup() {
  Wire.begin();
}

void loop() {
  Wire.beginTransmission(1);               
  Wire.write("good ");     
  Wire.write(x);           
  Wire.endTransmission();   
   
  delay(500);
 
  x++;
  if(x==6) x=0; 
}

---< I2C 통신 : 슬레이브에서 onReceive()를 이용하여 전송된 데이터 읽기 >----
#include <Wire.h>

void setup() {
  Serial.begin(9600);
  Wire.begin(1); //슬레이브 주소               
  Wire.onReceive(receiveEvent); //데이터 수신 받을 때 receiveEvent함수 호출

}

void loop() {
  delay(500);
}

void receiveEvent(int howMany) { //전송 데이터 읽기
  while (Wire.available()>1) {
    char ch = Wire.read();
    Serial.print(ch);       
  }
  int x = Wire.read();   
  Serial.println(x);     
}

---< I2C 통신 : 슬에이브로 마스터에서 requestFrom(1, 4)로 데이터 요청시 onRequest()로 데이터 전송 >----
#include <Wire.h>

void setup() {
  Wire.begin(1); //슬레이브 주소               
  Wire.onRequest(requestEvent); //요청시 requestEvent함수 호출

}

void loop() {
  delay(500);

}

void requestEvent() { //요청 시 수행 함수
  Wire.write("ok!\n"); 
}

---< I2C 통신 : 마스터로  requestFrom(1, 4)로 4byte 요청하고 슬레이브에서 데이터 송신  >----
#include <Wire.h>

void setup() {
  Wire.begin();
  Serial.begin(9600);
}

void loop() {
  Wire.requestFrom(1, 4); //슬레이브(1)에 4byte 요청
  while (Wire.available()) {
    char c = Wire.read();
    Serial.print(c);       
  }   
}