I2C device programming - Read data from I2C device


1. Define procedure on the emulator's side
  1. "Read" method of I2C device will request to device (or emulator) to read data so you need to define correspond procedure on the emulator.

  2. First, add some logic on the emulator side.

  3. Select "Emulator" tab.

  4. Add below script on the editor box.

      
    BindI2CComponent  
    	/Id:i2c1
    	/Procedure_OnRead:proc1
    
    procedure proc1
    
    	print "OnReadRequested: " + value.Length + " bytes"
    	
    	buff = Util.CreateArrayByte(2)
    	buff[0] = 0x31
    	buff[1] = 0x32
    
    	i2c1.SetReadBuffer(buff)
    end
    
      
 

  1. Above procedure will return two byte (0x31, 0x32) to application when it receives "Read" request from application.

  2. Click "Execute Script on the Emulator" button or Press "F5" key.



  3. Executed result:




2. Read byte[] data from I2C device
  1. Use "Read(byte[] buff)" method to read byte array data from I2C device.

  2. Before call this method, you should define a byte[] variable.

  3. "Read" method will request to device (or emulator) to read data so you need to define correspond procedure on the emulator.

  4. Select "Application" tab.

  5. Add below script on the editor box.

      
    rBuff = Util.CreateArrayByte(2)
    rBuff[0] = 0x01
    rBuff[1] = 0x01
    
    i2c1.Read(rBuff)
    
    res = Util.BytesToHex(rBuff)
    print res
    
      


  6. Util.BytesToHex(byte[]) method was used to convert byte[] array data into string of hex format.

  7. Click "Send to MF Application" button or Press "F5" key.

  8. Executed result: