您必须按照以下步骤在主 I2C 设备和从 I2C 设备之间进行通信:
- 只有 master 可以发起读或写请求。
- 读取或写入请求必须是同步的。这意味着,slave 只能在 master 请求它们之后返回数据,反之亦然。
- 不要使用 0 - 7 的从机地址。它们是保留的。使用范围在 8 到 127 之间的从地址。
- 在 Arduino I2C 上,您只能发送和接收一个字节。要发送或接收具有多个字节的整数、双精度,您需要先将它们拆分,另一方面,您必须将它们组合成等效的数据类型。(如我错了请纠正我。)
你的代码应该是这样的:
主草图:
#include <Wire.h>
#define SLAVE_ADDRESS 0x40
// This macro reads two byte from I2C slave and converts into equivalent int
#define I2C_ReadInteger(buf,dataInteger) \
buf[0] = Wire.read(); \
buf[1] = Wire.read(); \
dataInteger = *((int *)buf);
// Returns light intensity measured by 'SLAVE_ADDRESS' device
int GetLightIntensity()
{
byte Temp[2];
int Result;
// To get integer value from slave, two are required
int NumberOfBytes = 2;
// Request 'NumberOfBytes' from 'SLAVE_ADDRESS'
Wire.requestFrom(SLAVE_ADDRESS, NumberOfBytes);
// Call macro to read and convert bytes (Temp) to int (Result)
I2C_ReadInteger(Temp, Result);
return Result;
}
void setup()
{
// Initiate I2C Master
Wire.begin();
// Initiate Serial communication @ 9600 baud or of your choice
Serial.begin(9600);
}
void loop()
{
// Print light intensity at defined interval
Serial.print("Light Intensity = ");
Serial.println(GetLightIntensity());
delay(1000);
}
奴隶素描:
#include <Wire.h>
#define SLAVE_ADDRESS 0x40
#define inPin0 0
// Preapres 2-bytes equivalent to its int
#define IntegerToByte(buf,intData) \
*((int *)buf) = intData;
// Sends int to Master
void I2C_SendInteger(int Data)
{
byte Temp[2];
// I2C can only send a byte at a time.
// Int is of 2bytes and we need to split them into bytes
// in order to send it to Master.
// On Master side, it receives 2bytes and parses into
// equvivalent int.
IntegerToByte(Temp, Data);
// Write 2bytes to Master
Wire.write(Temp, 2);
}
void setup()
{
// Initiate I2C Slave @ 'SLAVE_ADDRESS'
Wire.begin(SLAVE_ADDRESS);
// Register callback on request by Master
Wire.onRequest(requestEvent);
}
void loop()
{
}
//
void requestEvent()
{
// Read sensor
int pinRead0 = analogRead(inPin0);
int pVolt0 = pinRead0 / 1024.0 * 5.0;
// Send int to Master
I2C_SendInteger(pVolt0);
}
此代码在 Arduino Version: 1.6.7上测试。有关 I2C 通信的更多信息,请参阅 Arduino 示例:主读卡器