master:
#include <Wire.h> // Comes with Arduino IDE
int x = 0;
void setup() {
// Start the I2C Bus as Master
Wire.begin();
}
void loop() {
//開始與9號裝置通訊
Wire.beginTransmission(9); // transmit to device #9
Wire.write(x); // sends x
Wire.endTransmission(); // stop transmitting
x++; // Increment x
if (x > 5)
x = 0; // reset x once it gets 6
delay(500);
}
slave:
#include <Wire.h> // Comes with Arduino IDE
#include <LiquidCrystal_I2C.h>
// addr, en,rw,rs,d4,d5,d6,d7,bl,blpol
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);// Set the LCD I2C address
int pos[]={0,0};
char *s="OPQR", *t="TCGS";
int x = 0;
int LED = 13;
void setup(){
//在IIC裡面註冊自己是9號裝置
Wire.begin(9);
Wire.onReceive(receiveEvent);
pos[0]=0;
pos[1]=0;
bgBlink();
lcd.backlight();
lcd.setCursor(0,0);
}
void receiveEvent(int bytes) {
x = Wire.read(); // read one character from the I2C
}
void loop(){
//If value received is 0 blink LED for 200 ms
if (x == '0') {
digitalWrite(LED, HIGH);
delay(200);
digitalWrite(LED, LOW);
delay(200);
}
//If value received is 3 blink LED for 400 ms
if (x == '3') {
digitalWrite(LED, HIGH);
delay(400);
digitalWrite(LED, LOW);
delay(400);
}
//showMsg(pos, s);
//pos[0]=1;
//pos[1]=1;
//showMsg(pos, s);
//delay(5000);
}
void bgBlink(){
lcd.begin(16,2);// initialize the lcd for 20 chars 4 lines and turn on backlight
for(int i = 0; i< 3; i++){
lcd.backlight();
delay(250);
lcd.noBacklight();
delay(250);
}
}
void showMsg(int *pos, int *arrt){
//(col,row)
lcd.setCursor(pos[0],pos[1]);
lcd.print(arrt[0]);
lcd.print(",");
lcd.print(arrt[1]);
}
void showMsg(int *pos, char *c){
int i;
lcd.setCursor(pos[0],pos[1]);
while(*c)
lcd.print(*c++);
}