NodeMCU与arduino Nano通过I2C通信

NodeMCU与arduino Nano通过I2C通信

接线方式

NodeMCU做主机程序如下:

#include <Wire.h>void setup() {
Serial.begin(9600);
Wire.begin(D1, D2);
}void loop() {
Wire.beginTransmission(8); 
Wire.write("Hello Arduino"); 
Wire.endTransmission(); Wire.requestFrom(8, 13); 
while(Wire.available()){char c = Wire.read();Serial.print(c);
}
Serial.println();
delay(1000);
}

arduino Nano作为从机

#include <Wire.h>void setup() {
Wire.begin(8);
Wire.onReceive(receiveEvent); 
Wire.onRequest(requestEvent); 
Serial.begin(9600);       
}void loop() {
delay(100);
}// function that executes whenever data is received from master
void receiveEvent(inthowMany) {
while (0 <Wire.available()) {char c = Wire.read();  Serial.print(c);          }
Serial.println();            
}
void requestEvent() {
Wire.write("Hello NodeMCU"); 
}

NodeMCU与arduino Nano通过I2C通信

NodeMCU与arduino Nano通过I2C通信

接线方式

NodeMCU做主机程序如下:

#include <Wire.h>void setup() {
Serial.begin(9600);
Wire.begin(D1, D2);
}void loop() {
Wire.beginTransmission(8); 
Wire.write("Hello Arduino"); 
Wire.endTransmission(); Wire.requestFrom(8, 13); 
while(Wire.available()){char c = Wire.read();Serial.print(c);
}
Serial.println();
delay(1000);
}

arduino Nano作为从机

#include <Wire.h>void setup() {
Wire.begin(8);
Wire.onReceive(receiveEvent); 
Wire.onRequest(requestEvent); 
Serial.begin(9600);       
}void loop() {
delay(100);
}// function that executes whenever data is received from master
void receiveEvent(inthowMany) {
while (0 <Wire.available()) {char c = Wire.read();  Serial.print(c);          }
Serial.println();            
}
void requestEvent() {
Wire.write("Hello NodeMCU"); 
}