writeRead Function

Top  Previous  Next

Sends and receives data on the SPI bus.

Syntax

Cell.SPI.writeRead(data [, count])

Arguments

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.

Remarks

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).

 

When using automatic control of the SS pin, the writeRead function is executed as a single transaction with SS going low at the start and returning high at completion. The current value of the config property determines which pin to use for SS. Therefore, if you have multiple devices on the SPI bus, you will need to set the value of the config property before using the writeRead function to set which pin to use for SS.

Examples

This example interfaces to an SST25VF512A EEPROM on the SPI bus with SS on pin B4 (as you would find on the Cell Development Kit).

 

// Read the manufacturer and device ID bytes

var id;

Cell.SPI.config = Cell.SPI.mode0 | 12; // SS on B4

Cell.SPI.bitRate = 16000000;

id = Cell.SPI.writeRead([0x90,0,0,0], 2);   // data is array

//id = Cell.SPI.writeRead("\x90\0\0\0", 2); // data is string

if (typeof id == "string")

{

 Net.write("Manufacturer ID: ", id[0].toString(16));

 Net.write("; Device ID: ", id[1].toString(16));

}

else

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

See Also

bitRate Property, Member Reference Operators, typeof Operator