Wire (Member Function Version)
This method using member functions has relatively low abstraction and follows a general API structure similar to that provided by C language libraries. It offers a more intuitive procedure for operating a two-wire serial bus.
However, you need to explicitly manage the start and end of bus usage.
Reading
requestFrom()
size_type requestFrom(
uint8_t u8address,
size_type length,
bool b_send_stop = true)
Reads a specified number of bytes in one operation. The result is stored in a queue, so you should call the .read()
method repeatedly until the queue is empty immediately afterward.
Parameter | Description |
---|---|
u8address | I2C address to read from |
length | Number of bytes to read |
b_send_stop=true | If true , a STOP bit is issued at the end of reading |
Return type size_type | Number of bytes read. 0 indicates failure |
Code Example
int len = Wire.requestFrom(0x70, 6);
for (int i = 0; i < 6; i++) {
if (Wire.available()) {
au8data[i] = Wire.read();
Serial.print(buff[i], HEX);
}
}
// skip the rest (just in case)
// while (Wire.available()) Wire.read(); // normally, not necessary.
Writing
The writing process starts with beginTransmission()
, then proceeds with the write()
method. After the entire write operation is complete, call endTransmission()
.
#define DEV_ADDR (0x70)
const uint8_t msg[2] =
{SHTC3_SOFT_RST_H, SHTC3_SOFT_RST_L};
Wire.beginTransmission(DEV_ADDR);
Wire.write(msg, sizeof(msg));
Wire.endTransmission();
beginTransmission()
void beginTransmission(uint8_t address)
Initializes a write transfer. After the write process, call endTransmission()
promptly.
Parameter | Description |
---|---|
u8address | I2C address to write to |
write(value)
size_type write(const value_type value)
Writes a single byte.
Parameter | Description |
---|---|
value | Byte to write |
Return size_type | Number of bytes written. 0 indicates an error. |
write(*value, quantity)
size_type write(
const value_type* value,
size_type quantity)
Writes a sequence of bytes.
Parameter | Description |
---|---|
*value | Byte sequence to write |
size_type | Number of bytes |
Return size_type | Number of bytes written. 0 indicates an error. |
endTransmission()
uint8_t endTransmission(bool sendStop = true)
Finalizes the write operation.
Parameter | Description |
---|---|
sendStop = true | Issues a STOP bit |
Return uint8_t | 0: success, 4: failure |