传感器i2c与arduino连接_Nodemcu I2C接口连接Arduino

I2C是一种是串行总线接口连接协议,它也被称为TWI(双线接口),因为它只使用两条线缆进行通信,这两条线分别是SDA(串行数据)和SCL(串行时钟)。I2C是一种即时应答的通信协议,即发送方在发送数据后即刻检查接收方的确认信号,以确定接收方是否成功的接收到数据。

I2C的工作模式

I2C的工作模式分为:主模式(Master mode)和从模式(Slave mode),主设备启动与从设备的通信。主设备需要从设备地址来启动与从设备的对话。当主设备寻址时,从设备响应主设备。主从设备在通信时,串行数据线(SDA)用于主从设备之间的数据交换。串行时钟(SCL)用于主从设备之间的时钟同步。

NodeMCU的GPIO引脚支持I2C功能。但由于ESP-12E的内部功能限制,我们不能使用它所有的GPIO来实现I2C功能。因此,在使用任何GPIO之前需要进行相关的测试。

Nodemcu I2C接口连接Arduino

下面我们来测试Nodemcu 通过I2C接口连接Arduino,将NodeMCU作为I2C 主设备, Arduino Uno作为I2C 从设备,主设备向从设备发送“hello”字符串,从设备向主设备发送“hello”字符串作为响应。

Nodemcu 通过 I2C 接口连接 Arduino

配置从设备地址为 8 。

NodeMCU (Master I2C Device)代码

#include

void setup() {

Serial.begin(9600); /* begin serial for debug */

Wire.begin(D1, D2); /* join i2c bus with SDA=D1 and SCL=D2 of NodeMCU */

}

void loop() {

Wire.beginTransmission(8); /* begin with device address 8 */

Wire.write("Hello Arduino"); /* sends hello string */

Wire.endTransmission(); /* stop transmitting */

Wire.requestFrom(8, 13); /* request & read data of size 13 from slave */

while(Wire.available()){

char c = Wire.read();

Serial.print(c);

}

Serial.println();

delay(1000);

}

Arduino Uno (Slave I2C Device) 代码

#include

void setup() {

Wire.begin(8); /* join i2c bus with address 8 */

Wire.onReceive(receiveEvent); /* register receive event */

Wire.onRequest(requestEvent); /* register request event */

Serial.begin(9600); /* start serial for debug */

}

void loop() {

delay(100);

}

// function that executes whenever data is received from master

void receiveEvent(int howMany) {

while (0

char c = Wire.read(); /* receive byte as a character */

Serial.print(c); /* print the character */

}

Serial.println(); /* to newline */

}

// function that executes whenever data is requested from master

void requestEvent() {

Wire.write("Hello NodeMCU"); /*send string on request */

}

从设备串口监视器输出(Arduino Uno)

从设备串口监视器输出

主设备串口监视器输出( NodeMCU )

主设备串口监视器输出

你可能感兴趣的:(传感器i2c与arduino连接_Nodemcu I2C接口连接Arduino)