I. Introduction of the interface
The internal integrated circuit (IIC or i²c) bus uses small data loads to connect simple external devices. Sensors and actuators are common examples of i²c use, including accelerometers, thermometers, LCD displays, and motor drives.
- The I²c Bus is a synchronous serial interface : This means that it relies on a shared clock signal to synchronize data transfer between devices. The device that controls the clock signal is called Master, and all other connected peripherals are considered slaves, and each device is connected to the same set of data signals to form the bus.
-
i²c Device Connection using 3-wire interface :
- Shared time signal (SCL);
- Shared data Line (SDA);
- Common grounding Reference (GND);
- I²c supports only half-duplex communication : Because all data is connected by a single line. All communications are initiated by the master device, and once the Master master transfer is complete slave must respond
- I²c supports connecting multiple slave devices on the same bus: Unlike spi,slave devices, they are addressed using the I²c software protocol. Each device is programmed with a unique address and responds only to the information that the master sends to the address. Each slave device must have an address, and the instant bus contains only a single signal slave.
second, the use of the interface1. Manage Slave device connections
Public class homeactivity extends Activity { //i²c Device Name Private Static FinalString i2c_device_name = ...;//i²c Slave Address Private Static Final intI2c_address = ...;PrivateI2cdevice Mdevice;@Override protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate);//Attempt to access the I²C device Try{Peripheralmanagerservice Manager =NewPeripheralmanagerservice (); Mdevice = Manager.openi2cdevice (I2c_device_name, i2c_address); }Catch(IOException e) {LOG.W (TAG,"Unable to access i²c device", e); } }}
2. Communication with registers
I²c slave device organizes content to a readable or writable register (a single byte of data is referenced by an address value):
- Readable register: Contains data that slave wants to report to master, such as sensor values or status identifiers;
- Writable Register: Contains configuration data that master can control;
A common protocol implementation known as System Management Bus (SMBus) exists at the top of the i²c to communicate in a standard manner and register. The SMBus command consists of the following two i²c transactions:
- The first transaction ID represents the address of the register to be accessed, and the second is the data read or written at that address.
- The logical data for a slave device may often occupy multiple bytes, which can contain multiple register addresses. The address provided to the API is always a reference to the first register;
Peripheral I/O provides three types of SMBUS commands to access registers:
- Byte data: Readregbyte () and Writeregbyte () to read or write a separate 8-bit register data.
- Word Data: Readregword () and Writeregword () to read or write two consecutive registers of values with a 16-bit litten-endian word. The address of the first register is translated to the smallest valid byte (LSB) in the word, followed by the most important byte (MSB).
- Block data: Readregbuffer () and Writeregbuffer () read or write values of up to 32 consecutive registers as an array.
//Modify The contents of a single register Public void Setregisterflag(I2cdevice device,intAddress) throws IOException {//Read one register from slave byte value= Device.readregbyte (address);//Set bit 6 value|=0x40;//Write The updated value back to SlaveDevice.writeregbyte (Address,value);}//Read a register block Public byte[]readcalibration(I2cdevice device,intstartaddress) throws IOException {//Read three consecutive register values byte[] data =New byte[3]; Device.readregbuffer (startaddress, data, data.length);returndata;}
3. Transferring raw data
When interacting with an i²c peripheral, a different SMBus register is defined, perhaps without a register at all, and the raw Raw () and write () methods are used to fully control the byte data passed through the wire. These methods will perform a separate i²c transfer as follows:
- With the original transfer, the device sends a launch condition before the transfer, and then a stop condition.
- It is not possible to combine multiple transmissions to a "repeat boot" condition;
publicvoidwriteBufferbytethrows IOException { int count = device.write(buffer, buffer.length); "Wrote "" bytes over I2C.");}
4. Close the connection
When you complete the I²C port communication, close this connection and release the resources. In addition, you cannot open a new connection until the existing port is closed. To close the connection, use the close () method of the port;
Public class homeactivity extends Activity {... ...PrivateI2cdevice Mdevice;@Override protected void OnDestroy() {Super. OnDestroy ();if(Mdevice! =NULL) {Try{Mdevice.close (); Mdevice =NULL; }Catch(IOException e) {LOG.W (TAG,"Unable to close i²c device", e); } } }}
Iii. Demonstration of the case
Below we use the I²c interface to obtain the temperature data of the bmp280 temperature sensor to demonstrate the use of the interface.
1. Hardware Preparation
- Raspberry Pi Development Board 1 pieces
- 1 Pieces of bread plate
- BMP280 sensor
- DuPont Line (male to female) several
Advertising Time: If you do not have their own development boards and components, to our "1024 Workshop micro Shop" to stroll around it (the bottom of the article QR code), here can buy you want!
2. Circuit Construction
3. Code writing
I2cdemo\app\src\main\java\com\chengxiang\i2cdemo\mainactivity.java
Public class mainactivity extends appcompatactivity { Private Static FinalString i2c_address ="I2C1";Private Static Final intTemperature_sensor_slave =0x77;Private Static Final intRegister_temperature_calibration_1 =0x88;Private Static Final intRegister_temperature_calibration_2 =0x8A;Private Static Final intRegister_temperature_calibration_3 =0x8c;Private Static Final intRegister_temperature_raw_value_start =0xFA;Private Static Final intRegister_temperature_raw_value_size =3;PrivateTextView Temperaturetextview;PrivateI2cdevice I2cdevice;Private Final Short[] Calibrationdata =New Short[3];@Override protected void onCreate(Bundle savedinstancestate) {Super. OnCreate (Savedinstancestate); Setcontentview (R.layout.activity_main); Temperaturetextview = (TextView) Findviewbyid (r.id.temperature); Peripheralmanagerservice Peripheralmanagerservice =NewPeripheralmanagerservice ();Try{I2cdevice = Peripheralmanagerservice.openi2cdevice (i2c_address, Temperature_sensor_slave); calibrationdata[0] = I2cdevice.readregword (register_temperature_calibration_1); calibrationdata[1] = I2cdevice.readregword (register_temperature_calibration_2); calibrationdata[2] = I2cdevice.readregword (register_temperature_calibration_3);byte[] data =New byte[Register_temperature_raw_value_size]; I2cdevice.readregbuffer (Register_temperature_raw_value_start, data, register_temperature_raw_value_size);if(Data.length! =0) {floatTemperature = Compensatetemperature (Readsample (data)); Temperaturetextview.settext ("Temperature:"+ temperature); } }Catch(IOException e) {E.printstacktrace (); } }@Override protected void OnDestroy() {Super. OnDestroy ();if(I2cdevice! =NULL) {Try{I2cdevice.close (); I2cdevice =NULL; }Catch(IOException e) {LOG.W (TAG,"Unable to close i²c device", e); } } }Private int Readsample(byte[] data) {//msb[7:0] lsb[7:0] Xlsb[7:4] intMSB = data[0] &0xFF;intLSB = data[1] &0xFF;intXLSB = data[2] &0xf0;//Convert to 20bit integer return(MSB << -| LSB <<8| XLSB) >>4; }Private float compensatetemperature(intRawtemp) {floatDigT1 = calibrationdata[0];floatDigT2 = calibrationdata[1];floatDigT3 = calibrationdata[2];floatAdcT = (float) Rawtemp;floatVarX1 = AdcT/16384F-DIGT1/1024x768FfloatvarX2 = varX1 * DIGT2;floatVarY1 = AdcT/131072F-DIGT1/8192FfloatvarY2 = varY1 * VARY1;floatvarY3 = varY2 * DIGT3;return(varX2 + varY3)/5120F }}
4. Running Results
According to the above circuit diagram, the building circuit is as follows:
To run the program, the temperature detected by the sensor is displayed on the screen:
1. New Technology, future! You are welcome to pay attention to the "1024 Workshop" service number, always pay attention to our latest technical information. (Don't hesitate!) Enjoy the scan or long press! )
2. Discard all kinds of trouble to find components, to "1024 workshop" micro-shop, buy what you want at once. (Don't hesitate!) Enjoy the scan or long press! )
3. Join "Android things development" QQ discussion group, learn together hi. (Don't hesitate!) Enjoy the scan or long press! )
Android things: Peripheral I/O interface-i2c