Arduino

아두이노 간 I2C 다중 통신하기

작성자 임베디드코리아 작성일25-05-16 00:40 조회184회 댓글0건

첨부파일

<* 아두이노 간 I2C  다중 통신하기 *>
◎ 마스터에 슬레이브를 여러 개 연결하여 사용한다.

-------< I2C  마스터 소스 코드 > ------------------------------------------
#include <Wire.h>

// 슬레이브 주소
int SLAVE[4] = {1, 2, 3, 4};

void setup() {
  // Wire 라이브러리 초기화
  Wire.begin();
  // 직렬 통신 초기화
  Serial.begin(9600);
}

void loop() {
  if (Serial.available()) {
    char e = Serial.read();
    byte c = e - 48;
    if (c < 5) {
      // I2C 통신을 통한 전송 시작
      Wire.beginTransmission(SLAVE[c-1]);
      // 슬레이브 주소를 시리얼 창에 입력시 해당 시리얼 주소로 'o'문자와 데이터 요구를 보냅니다.
      Wire.write('o');
      Wire.write('\n');
      Wire.endTransmission(SLAVE[c-1]);
     
      delay(10);
      // 슬레이브로 데이터 요구 및 수신 데이터 처리
      i2c_communication(c-1);
      delay(10);
    }
  }
}

void i2c_communication(int i) {
  // 12 바이트 크기의 데이터 요청
  Wire.requestFrom(SLAVE[i], 12);
  // 12 바이트 모두 출력할 때까지 반복
  for (int j = 0 ; j < 12 ; j++) { 
    // 수신 데이터 읽기
    char c = Wire.read();
    // 수신 데이터 출력
    Serial.print(c);
  }
  Serial.println();
}

-------- < I2C 슬레이브 소스 코드 > --------------------------------------------------
#include <Wire.h>

// 자신의 슬레이브 주소를 설정해 줍니다.(슬레이브 주소에 맞게 수정해야 합니다.)
#define SLAVE 4 

// 카운터
byte count = 0;
char temp;

void setup() {
  // Wire 라이브러리 초기화
  // 슬레이브로 참여하기 위해서는 주소를 지정해야 한다.
  Wire.begin(SLAVE);
  Wire.onReceive(receiveFromMaster);
  // 마스터의 데이터 전송 요구가 있을 때 처리할 함수 등록
  Wire.onRequest(sendToMaster);
  pinMode(13, OUTPUT);
  Serial.begin(9600);
}

void loop () {
  // 요청이 들어오면 13번 LED를 0.5초간 켜줍니다.
  if (temp == 'o') {
    play();
  }
}

void receiveFromMaster(int bytes) {
  char ch[2];
  for (int i = 0 ; i < bytes ; i++) {
    // 수신 버퍼 읽기
    ch[i] = Wire.read();
  }
  temp = ch[0];
}

void play() {
  digitalWrite(13, HIGH);
  delay(500);
  digitalWrite(13, LOW);
  temp = 0;
}

void sendToMaster() {
  // 자신의 슬레이브 주소를 담은 메세지를 마스터에게 보냅니다. 슬레이브 주소에 맞게 수정해야 합니다.
  Wire.write("4th Arduino ");
}