이번 실험은 마스터에서 슬레이브의 센서 값을 읽어오는 시험이다. 마스터에 있는 버튼을 누르면 마스터는 지정된 슬레이브에 자료를 요청한다. 슬레이브는 마스터로부터 요청이 있는지를 검사하여 요청이 있을 경우, 해당된 데이터를 마스터로 보낸다.

#include <Wire.h>
const int button1Pin = 2; // push button을 디지털 2번 핀에 연결
const int ledPin = 13; // led 를 디지털 13번 핀에 연결
int button1State = 0; // 버튼에서 읽어 올 디지털 값을 저장
void setup() {
Wire.begin();
Serial.begin(9600);
pinMode(button1Pin, INPUT); //2번 핀을 입력 핀으로 설정
pinMode(ledPin, OUTPUT); //13번 핀을 출력 핀으로 설정
}
void loop() {
// 버튼의 상태를 읽고 변수에 저장
button1State = digitalRead(button1Pin);
// 버튼이 눌렸다면
if(button1State == LOW){
// i2c통신으로 센서값(습도) 요청
Wire.beginTransmission(18);
Wire.write('H');
Wire.endTransmission();
Wire.requestFrom(18, 2);
byte response[2];
int index = 0;
// 센서값 받기를 기다림
while (Wire.available()) {
byte b = Wire.read();
Serial.println(int(b));
}
digitalWrite (ledPin, HIGH);
//Serial.println("Botton on");
delay(1000);
}
else{ // 버튼이 눌리지 않았다면
digitalWrite(ledPin, LOW);
}
delay(100);
}
#include "DHT.h" // DHT.h 라이브러리를 포함한다
#include <Wire.h>
#define DHTPIN 2 // DHT핀을 2번으로 정의한다(DATA핀)
#define DHTTYPE DHT11 // DHT타입을 DHT11로 정의한다
DHT dht(DHTPIN, DHTTYPE); // DHT설정 - dht (디지털2, dht11)
char c;
int h;
int t;
void setup() {
Wire.begin(18);
Wire.onRequest(requestEvent); // data request to slave
Wire.onReceive(receiveEvent); // data slave received
Serial.begin(9600); // 9600 속도로 시리얼 통신을 시작한다.
}
void loop() {
h = dht.readHumidity(); // 변수 h에 습도 값을 저장
t = dht.readTemperature(); // 변수 t에 온도 값을 저장
Serial.print("Humidity: "); // 문자열 Humidity: 를 출력한다.
Serial.print(h); // 변수 h(습도)를 출력한다.
Serial.print("%\t"); // %를 출력한다.
Serial.print("Temperature: "); // 이하생략
Serial.print(t);
Serial.println(" C");
delay(1000);
}
void receiveEvent(int howMany) {
// remember the question: H=humidity, T=temperature
while (0 < Wire.available()) {
byte x = Wire.read();
c = x;
Serial.println(c);
}
}
void requestEvent() {
// respond to the question
if (c == 'H') {
Wire.write(h);
Serial.print("Current humidity =");
Serial.println(h);
}
else {
Wire.write(t);
Serial.print("Current temperature =");
Serial.println(t);
}
}
마스터에서 버튼을 누르면, 마스터는 버튼이 눌러진 상태를
LED(13번)를 이용하여 나타낸다. 동시에 마스터는슬레이브(18)를 지정하며,'H'신호를 보낸다. 그리고 지정된 슬레이브에게requestFrom()함수를 이용하여 자료를 요청한다. 마스터는 지정된 슬레이브로부터 보내온 데이터를 읽어서 시리얼 모니터를 통해 확인할 수 있다.
슬레이브는 매 초마다 센서 값을 읽어서 저장한다.receiveEvent()함수는 마스터로부터 보내온 데이터를 읽어서 변수 c에 저장한다. 그리고requestEvent()를 이용하여 보내온 데이터를 확인하여 센서값을 마스터로 보낸다. 마스터는 수신된 데이터를 시리얼 모니터를 통하여 표시된다.


