1. i2c communication between Arduino master and slave
I2C bus definition: I2C ('intel'-Integrated Circuit) bus is a two-wire serial bus developed by PHILIPS, used to connect microcontrollers and their peripheral devices. In the master-slave communication, there can be multiple I2C bus devices connected to the I2C bus at the same time, and the communication object is identified by the address.
The I2C bus is a serial bus composed of a data line SDA and a clock SCL, which can send and receive data. Bidirectional transmission is performed between the CPU and the controlled IC, and between the IC and the IC, with a maximum transmission rate of 100kbps. Various controlled circuits are connected in parallel on this bus, but just like a telephone, it can only work by dialing their respective numbers, so each circuit and module has a unique address . In the process of information transmission, on the I2C bus Each module circuit connected in parallel can be either a master controller (or a controlled device) or a transmitter (or receiver), depending on the function it needs to complete. 2. Wire Library
This library allows you to communicate with I2C/TWI devices. On the Arduino board the R3 layout (1.0 pinout), SDA (data line) and SCL (clock line) are all on the header close to the AREF pin. The Arduino Due has two I2C/TWI interfaces SDA1 and SCL1 close to the AREF pin and the other one on 20 and 21. Details can be found here: https://www.arduino.cc/en/Reference/Wire
Note: Pull-up resistors need to be connected when connecting SDA/SCL pins, mega2560 pull-up resistors are on pins 20-21. (No additional settings, debugging is successful, the reason is unknown for the time being?)
Functions
- begin()
- requestFrom()
- startTransmission ()
- endTransmission()
- write()
- available()
- read()
- SetClock()
- onReceive()
- onRequest()
3. Test demo
Pin Connection:
1 VCC ------ VCC
2 GND ------ GND
3 SCL ------ 21(SCL) or SCL1
4 SDA------20(SDA)or SDA1
code
#include <Wire.h> void setup() { // put your setup code here, to run once: Wire.begin(); // join i2c bus (address optional for master) Serial.begin(9600); // start serial for output } uint16_t result; float temp; void loop() { // put your main code here, to run repeatedly: Wire.beginTransmission(0x5A); Wire.write(0x07); // sends instruction byte Wire.endTransmission(false); // stop transmitting Wire.requestFrom(0x5A, 3);//Send data n-bytes read result = Wire.read(); //Receive DATA result |= Wire.read() << 8; //Receive DATA uint8_t pec = Wire.read(); temp = result*0.02-273.15;// Serial.print(temp); Serial.println(); // delay(500); }
Test Results: