writeRead Function

Top  Previous  Next

Sends and receives data on the I²C bus.


Cell.I2C.writeRead(address, data [, count])


addressThe address of the device.
dataData to send to the device. Can be undefined, a single byte, a string, or an array.
countAn optional integer specifying the number of bytes to receive; zero if omitted.

Return Value

A string of length count with the received data, or a negative number if error.


The device address is the upper 7 bits of the address byte, so address is always even.


To receive data without sending any, data should be the value undefined. To send a single byte, data should be the byte value. To send multiple bytes, data can be an array of byte values or a string whose characters are the byte values. In either case, the entire array or string is sent.


To receive data, count must be set to the number of bytes to receive. The received data will be returned in a string of count characters. If count is zero or omitted, the empty string is returned on success. To access the individual bytes of the return string, use the element reference operator [].


If there is an error, the function returns a negative number. You should use the typeof operator to determine if the result is a string (success) or a number (failure).


This example interfaces to an LM73 temperature sensor on the I²C bus (as you would find on the Cell Development Kit). First the LM73 control register is written to change the resolution to 12 bits. Then the temperature value is read. Per the LM73 data sheet, this value is in two bytes, most significant first, representing temperature in degrees C multiplied by 128. It is negative if the MSB is set.


var addr, temp, tempF;

addr = 0x92;// LM73-0 with ADDR pin grounded

Cell.I2C.bitRate = 400000;


// Write register 0x04 to set resolution to 12 bits

Cell.I2C.writeRead(addr, [0x04, 0x20]);  // data is array

//Cell.I2C.writeRead(addr, "\x04\x20");  // data is string


// Read temperature from register 0x00

temp = Cell.I2C.writeRead(addr, 0, 2);

// ...

// For LM73, don't need to set register again

temp = Cell.I2C.writeRead(addr, undefined, 2);


if (typeof temp == "string")


 // Convert two-character string result to temperature

 temp = (temp[0] << 8) | temp[1];

 if (temp & 0x8000)

   temp |= 0xFFFF0000;// sign-extend negative value

 temp = temp / 128;

 tempF = temp * 9 / 5 + 32;

 Net.write("LM73 temperature reading: ", temp, " C, ", tempF, " F");



 Net.write("Failed to read LM73");

See Also

bitRate Property, Member Reference Operators, typeof Operator