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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值