I2C的使用

I2C的使用

I2C用通过总线通信将多个设备连接在一起,可以解决数据接口缺少的问题,是不同单片机间实现通信的一种方式
在arduino中设有SDA /SCL接口。这些接口在板子上有预定义的,当然也可以自己定义这种接口。
需查看所使用设备的电子线路图来设置SDA/SCL的通信接口。
WEMOS (SDA=D14=4 / SCL=D15=5)
在使用过程中分为主从。目前来看主端需要定义两个端口的PIN值,从端不必
主从两端都需要定义设备号

主端

setup

Wire.begin(SDA_PIN,SCL_PIN,I2C_MASTER);

运行中

Wire.requestFrom(I2C_SLAVE,9);格式为从slave端读取9个字节的数据
while(Wire.available()){//监测Wire的有效性
char c=Wire.read(); //接收一个字节的字符数据

Wire.beginTransmission(I2C_SLAVE) //开始传送数据给从设备
Wire.write("x is ");
Wire.write(x);
Wire.endTransmission();//停止数据传送

从端

setup

Wire.begin(I2C_SLAVE);
Wire.onReceive(receiveEvent);

loop

Wire.onRequest(requestEvent);

receiveEvent(Args)

while(Wire.available()>1)
{char c=Wire.read();}

requestEvent()

Wire.write(s.c_str()); //send message to master

s.c_str()
Converts the contents of a string as a C-style, null-terminated string. Note that this gives direct access to the internal String buffer and should be used with care. In particular, you should never modify the string through the pointer returned. When you modify the String object, or when it is destroyed, any pointer previously returned by c_str() becomes invalid and should not be used any longer.

你可能感兴趣的:(arduino)